@shivaedev/platform 0.34.0 → 0.35.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 (403) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +35 -907
  3. package/package.json +33 -68
  4. package/dist/http-client/body.d.ts +0 -7
  5. package/dist/http-client/body.d.ts.map +0 -1
  6. package/dist/http-client/body.js +0 -32
  7. package/dist/http-client/body.js.map +0 -1
  8. package/dist/http-client/errors.d.ts +0 -51
  9. package/dist/http-client/errors.d.ts.map +0 -1
  10. package/dist/http-client/errors.js +0 -25
  11. package/dist/http-client/errors.js.map +0 -1
  12. package/dist/http-client/filterStatus.d.ts +0 -4
  13. package/dist/http-client/filterStatus.d.ts.map +0 -1
  14. package/dist/http-client/filterStatus.js +0 -38
  15. package/dist/http-client/filterStatus.js.map +0 -1
  16. package/dist/http-client/nextLink.d.ts +0 -2
  17. package/dist/http-client/nextLink.d.ts.map +0 -1
  18. package/dist/http-client/nextLink.js +0 -11
  19. package/dist/http-client/nextLink.js.map +0 -1
  20. package/dist/http-client/paginate.d.ts +0 -5
  21. package/dist/http-client/paginate.d.ts.map +0 -1
  22. package/dist/http-client/paginate.js +0 -31
  23. package/dist/http-client/paginate.js.map +0 -1
  24. package/dist/http-client/parseRetryAfter.d.ts +0 -3
  25. package/dist/http-client/parseRetryAfter.d.ts.map +0 -1
  26. package/dist/http-client/parseRetryAfter.js +0 -17
  27. package/dist/http-client/parseRetryAfter.js.map +0 -1
  28. package/dist/rpc/identity.d.ts +0 -36
  29. package/dist/rpc/identity.d.ts.map +0 -1
  30. package/dist/rpc/identity.js +0 -12
  31. package/dist/rpc/identity.js.map +0 -1
  32. package/dist/rpc/middleware.d.ts +0 -21
  33. package/dist/rpc/middleware.d.ts.map +0 -1
  34. package/dist/rpc/middleware.js +0 -20
  35. package/dist/rpc/middleware.js.map +0 -1
  36. package/dist/rpc/permission.d.ts +0 -11
  37. package/dist/rpc/permission.d.ts.map +0 -1
  38. package/dist/rpc/permission.js +0 -17
  39. package/dist/rpc/permission.js.map +0 -1
  40. package/dist/rpc/publicConfig.d.ts +0 -20
  41. package/dist/rpc/publicConfig.d.ts.map +0 -1
  42. package/dist/rpc/publicConfig.js +0 -8
  43. package/dist/rpc/publicConfig.js.map +0 -1
  44. package/dist/rpc/userRoles.d.ts +0 -44
  45. package/dist/rpc/userRoles.d.ts.map +0 -1
  46. package/dist/rpc/userRoles.js +0 -20
  47. package/dist/rpc/userRoles.js.map +0 -1
  48. package/dist/server/AppHostFactory.d.ts +0 -15
  49. package/dist/server/AppHostFactory.d.ts.map +0 -1
  50. package/dist/server/AppHostFactory.js +0 -2
  51. package/dist/server/AppHostFactory.js.map +0 -1
  52. package/dist/server/AppHostInput.d.ts +0 -13
  53. package/dist/server/AppHostInput.d.ts.map +0 -1
  54. package/dist/server/AppHostInput.js +0 -2
  55. package/dist/server/AppHostInput.js.map +0 -1
  56. package/dist/server/MigrationOptions.d.ts +0 -15
  57. package/dist/server/MigrationOptions.d.ts.map +0 -1
  58. package/dist/server/MigrationOptions.js +0 -2
  59. package/dist/server/MigrationOptions.js.map +0 -1
  60. package/dist/server/RedactionPolicy.d.ts +0 -4
  61. package/dist/server/RedactionPolicy.d.ts.map +0 -1
  62. package/dist/server/RedactionPolicy.js +0 -4
  63. package/dist/server/RedactionPolicy.js.map +0 -1
  64. package/dist/server/appHost.d.ts +0 -47
  65. package/dist/server/appHost.d.ts.map +0 -1
  66. package/dist/server/appHost.js +0 -17
  67. package/dist/server/appHost.js.map +0 -1
  68. package/dist/server/appHostHttp.d.ts +0 -88
  69. package/dist/server/appHostHttp.d.ts.map +0 -1
  70. package/dist/server/appHostHttp.js +0 -67
  71. package/dist/server/appHostHttp.js.map +0 -1
  72. package/dist/server/better-auth/adapter.d.ts +0 -10
  73. package/dist/server/better-auth/adapter.d.ts.map +0 -1
  74. package/dist/server/better-auth/adapter.js +0 -57
  75. package/dist/server/better-auth/adapter.js.map +0 -1
  76. package/dist/server/better-auth/allowedAccounts.d.ts +0 -10
  77. package/dist/server/better-auth/allowedAccounts.d.ts.map +0 -1
  78. package/dist/server/better-auth/allowedAccounts.js +0 -20
  79. package/dist/server/better-auth/allowedAccounts.js.map +0 -1
  80. package/dist/server/better-auth/bearerSessions.d.ts +0 -9
  81. package/dist/server/better-auth/bearerSessions.d.ts.map +0 -1
  82. package/dist/server/better-auth/bearerSessions.js +0 -38
  83. package/dist/server/better-auth/bearerSessions.js.map +0 -1
  84. package/dist/server/better-auth/memoryRateLimit.d.ts +0 -3
  85. package/dist/server/better-auth/memoryRateLimit.d.ts.map +0 -1
  86. package/dist/server/better-auth/memoryRateLimit.js +0 -46
  87. package/dist/server/better-auth/memoryRateLimit.js.map +0 -1
  88. package/dist/server/better-auth/mount.d.ts +0 -265
  89. package/dist/server/better-auth/mount.d.ts.map +0 -1
  90. package/dist/server/better-auth/mount.js +0 -111
  91. package/dist/server/better-auth/mount.js.map +0 -1
  92. package/dist/server/better-auth/mountRoutes.d.ts +0 -22
  93. package/dist/server/better-auth/mountRoutes.d.ts.map +0 -1
  94. package/dist/server/better-auth/mountRoutes.js +0 -54
  95. package/dist/server/better-auth/mountRoutes.js.map +0 -1
  96. package/dist/server/better-auth/mountedSessions.d.ts +0 -15
  97. package/dist/server/better-auth/mountedSessions.d.ts.map +0 -1
  98. package/dist/server/better-auth/mountedSessions.js +0 -12
  99. package/dist/server/better-auth/mountedSessions.js.map +0 -1
  100. package/dist/server/better-auth/relation.d.ts +0 -27
  101. package/dist/server/better-auth/relation.d.ts.map +0 -1
  102. package/dist/server/better-auth/relation.js +0 -31
  103. package/dist/server/better-auth/relation.js.map +0 -1
  104. package/dist/server/better-auth/revokeUnadmitted.d.ts +0 -10
  105. package/dist/server/better-auth/revokeUnadmitted.d.ts.map +0 -1
  106. package/dist/server/better-auth/revokeUnadmitted.js +0 -29
  107. package/dist/server/better-auth/revokeUnadmitted.js.map +0 -1
  108. package/dist/server/better-auth/rowAdapter.d.ts +0 -8
  109. package/dist/server/better-auth/rowAdapter.d.ts.map +0 -1
  110. package/dist/server/better-auth/rowAdapter.js +0 -52
  111. package/dist/server/better-auth/rowAdapter.js.map +0 -1
  112. package/dist/server/better-auth/sessionPermissions.d.ts +0 -3
  113. package/dist/server/better-auth/sessionPermissions.d.ts.map +0 -1
  114. package/dist/server/better-auth/sessionPermissions.js +0 -16
  115. package/dist/server/better-auth/sessionPermissions.js.map +0 -1
  116. package/dist/server/better-auth/signInGate.d.ts +0 -37
  117. package/dist/server/better-auth/signInGate.d.ts.map +0 -1
  118. package/dist/server/better-auth/signInGate.js +0 -38
  119. package/dist/server/better-auth/signInGate.js.map +0 -1
  120. package/dist/server/better-auth/signInPolicy.d.ts +0 -193
  121. package/dist/server/better-auth/signInPolicy.d.ts.map +0 -1
  122. package/dist/server/better-auth/signInPolicy.js +0 -61
  123. package/dist/server/better-auth/signInPolicy.js.map +0 -1
  124. package/dist/server/better-auth/testDatabase.d.ts +0 -19
  125. package/dist/server/better-auth/testDatabase.d.ts.map +0 -1
  126. package/dist/server/better-auth/testDatabase.js +0 -24
  127. package/dist/server/better-auth/testDatabase.js.map +0 -1
  128. package/dist/server/better-auth/testing.d.ts +0 -24
  129. package/dist/server/better-auth/testing.d.ts.map +0 -1
  130. package/dist/server/better-auth/testing.js +0 -21
  131. package/dist/server/better-auth/testing.js.map +0 -1
  132. package/dist/server/better-auth/userProfiles.d.ts +0 -14
  133. package/dist/server/better-auth/userProfiles.d.ts.map +0 -1
  134. package/dist/server/better-auth/userProfiles.js +0 -20
  135. package/dist/server/better-auth/userProfiles.js.map +0 -1
  136. package/dist/server/better-auth/users.d.ts +0 -24
  137. package/dist/server/better-auth/users.d.ts.map +0 -1
  138. package/dist/server/better-auth/users.js +0 -65
  139. package/dist/server/better-auth/users.js.map +0 -1
  140. package/dist/server/better-auth/where.d.ts +0 -22
  141. package/dist/server/better-auth/where.d.ts.map +0 -1
  142. package/dist/server/better-auth/where.js +0 -105
  143. package/dist/server/better-auth/where.js.map +0 -1
  144. package/dist/server/boundedBody.d.ts +0 -14
  145. package/dist/server/boundedBody.d.ts.map +0 -1
  146. package/dist/server/boundedBody.js +0 -36
  147. package/dist/server/boundedBody.js.map +0 -1
  148. package/dist/server/boundedRpcRequest.d.ts +0 -3
  149. package/dist/server/boundedRpcRequest.d.ts.map +0 -1
  150. package/dist/server/boundedRpcRequest.js +0 -22
  151. package/dist/server/boundedRpcRequest.js.map +0 -1
  152. package/dist/server/commandChanges.d.ts +0 -5
  153. package/dist/server/commandChanges.d.ts.map +0 -1
  154. package/dist/server/commandChanges.js +0 -44
  155. package/dist/server/commandChanges.js.map +0 -1
  156. package/dist/server/databaseAddress.d.ts +0 -4
  157. package/dist/server/databaseAddress.d.ts.map +0 -1
  158. package/dist/server/databaseAddress.js +0 -25
  159. package/dist/server/databaseAddress.js.map +0 -1
  160. package/dist/server/databaseLayer.d.ts +0 -14
  161. package/dist/server/databaseLayer.d.ts.map +0 -1
  162. package/dist/server/databaseLayer.js +0 -100
  163. package/dist/server/databaseLayer.js.map +0 -1
  164. package/dist/server/development.d.ts +0 -10
  165. package/dist/server/development.d.ts.map +0 -1
  166. package/dist/server/development.js +0 -20
  167. package/dist/server/development.js.map +0 -1
  168. package/dist/server/healthRoute.d.ts +0 -3
  169. package/dist/server/healthRoute.d.ts.map +0 -1
  170. package/dist/server/healthRoute.js +0 -18
  171. package/dist/server/healthRoute.js.map +0 -1
  172. package/dist/server/hostChanges.d.ts +0 -7
  173. package/dist/server/hostChanges.d.ts.map +0 -1
  174. package/dist/server/hostChanges.js +0 -25
  175. package/dist/server/hostChanges.js.map +0 -1
  176. package/dist/server/hostOptions.d.ts +0 -34
  177. package/dist/server/hostOptions.d.ts.map +0 -1
  178. package/dist/server/hostOptions.js +0 -2
  179. package/dist/server/hostOptions.js.map +0 -1
  180. package/dist/server/hostTransport.d.ts +0 -16
  181. package/dist/server/hostTransport.d.ts.map +0 -1
  182. package/dist/server/hostTransport.js +0 -16
  183. package/dist/server/hostTransport.js.map +0 -1
  184. package/dist/server/nativeClientOrigins.d.ts +0 -4
  185. package/dist/server/nativeClientOrigins.d.ts.map +0 -1
  186. package/dist/server/nativeClientOrigins.js +0 -38
  187. package/dist/server/nativeClientOrigins.js.map +0 -1
  188. package/dist/server/node-http/subscriptionSignal.d.ts +0 -12
  189. package/dist/server/node-http/subscriptionSignal.d.ts.map +0 -1
  190. package/dist/server/node-http/subscriptionSignal.js +0 -55
  191. package/dist/server/node-http/subscriptionSignal.js.map +0 -1
  192. package/dist/server/otlpHttpClient.d.ts +0 -4
  193. package/dist/server/otlpHttpClient.d.ts.map +0 -1
  194. package/dist/server/otlpHttpClient.js +0 -36
  195. package/dist/server/otlpHttpClient.js.map +0 -1
  196. package/dist/server/otlpTracing.d.ts +0 -3
  197. package/dist/server/otlpTracing.d.ts.map +0 -1
  198. package/dist/server/otlpTracing.js +0 -35
  199. package/dist/server/otlpTracing.js.map +0 -1
  200. package/dist/server/redactOtlpUrl.d.ts +0 -2
  201. package/dist/server/redactOtlpUrl.d.ts.map +0 -1
  202. package/dist/server/redactOtlpUrl.js +0 -41
  203. package/dist/server/redactOtlpUrl.js.map +0 -1
  204. package/dist/server/redactingDiagnostics.d.ts +0 -5
  205. package/dist/server/redactingDiagnostics.d.ts.map +0 -1
  206. package/dist/server/redactingDiagnostics.js +0 -25
  207. package/dist/server/redactingDiagnostics.js.map +0 -1
  208. package/dist/server/redactingRpcSerialization.d.ts +0 -4
  209. package/dist/server/redactingRpcSerialization.d.ts.map +0 -1
  210. package/dist/server/redactingRpcSerialization.js +0 -74
  211. package/dist/server/redactingRpcSerialization.js.map +0 -1
  212. package/dist/server/redactingTracer.d.ts +0 -4
  213. package/dist/server/redactingTracer.d.ts.map +0 -1
  214. package/dist/server/redactingTracer.js +0 -32
  215. package/dist/server/redactingTracer.js.map +0 -1
  216. package/dist/server/rpc-server/adapters/betterAuthSessions.d.ts +0 -14
  217. package/dist/server/rpc-server/adapters/betterAuthSessions.d.ts.map +0 -1
  218. package/dist/server/rpc-server/adapters/betterAuthSessions.js +0 -24
  219. package/dist/server/rpc-server/adapters/betterAuthSessions.js.map +0 -1
  220. package/dist/server/rpc-server/boundary.d.ts +0 -9
  221. package/dist/server/rpc-server/boundary.d.ts.map +0 -1
  222. package/dist/server/rpc-server/boundary.js +0 -18
  223. package/dist/server/rpc-server/boundary.js.map +0 -1
  224. package/dist/server/rpc-server/local.d.ts +0 -10
  225. package/dist/server/rpc-server/local.d.ts.map +0 -1
  226. package/dist/server/rpc-server/local.js +0 -93
  227. package/dist/server/rpc-server/local.js.map +0 -1
  228. package/dist/server/rpc-server/origin.d.ts +0 -15
  229. package/dist/server/rpc-server/origin.d.ts.map +0 -1
  230. package/dist/server/rpc-server/origin.js +0 -16
  231. package/dist/server/rpc-server/origin.js.map +0 -1
  232. package/dist/server/rpc-server/permissions.d.ts +0 -9
  233. package/dist/server/rpc-server/permissions.d.ts.map +0 -1
  234. package/dist/server/rpc-server/permissions.js +0 -31
  235. package/dist/server/rpc-server/permissions.js.map +0 -1
  236. package/dist/server/rpc-server/proxyRanges.d.ts +0 -4
  237. package/dist/server/rpc-server/proxyRanges.d.ts.map +0 -1
  238. package/dist/server/rpc-server/proxyRanges.js +0 -62
  239. package/dist/server/rpc-server/proxyRanges.js.map +0 -1
  240. package/dist/server/rpc-server/publicConfigLayer.d.ts +0 -4
  241. package/dist/server/rpc-server/publicConfigLayer.d.ts.map +0 -1
  242. package/dist/server/rpc-server/publicConfigLayer.js +0 -9
  243. package/dist/server/rpc-server/publicConfigLayer.js.map +0 -1
  244. package/dist/server/rpc-server/redact.d.ts +0 -4
  245. package/dist/server/rpc-server/redact.d.ts.map +0 -1
  246. package/dist/server/rpc-server/redact.js +0 -64
  247. package/dist/server/rpc-server/redact.js.map +0 -1
  248. package/dist/server/rpc-server/redactCause.d.ts +0 -7
  249. package/dist/server/rpc-server/redactCause.d.ts.map +0 -1
  250. package/dist/server/rpc-server/redactCause.js +0 -92
  251. package/dist/server/rpc-server/redactCause.js.map +0 -1
  252. package/dist/server/rpc-server/resolveRole.d.ts +0 -11
  253. package/dist/server/rpc-server/resolveRole.d.ts.map +0 -1
  254. package/dist/server/rpc-server/resolveRole.js +0 -6
  255. package/dist/server/rpc-server/resolveRole.js.map +0 -1
  256. package/dist/server/rpc-server/revalidateStream.d.ts +0 -6
  257. package/dist/server/rpc-server/revalidateStream.d.ts.map +0 -1
  258. package/dist/server/rpc-server/revalidateStream.js +0 -19
  259. package/dist/server/rpc-server/revalidateStream.js.map +0 -1
  260. package/dist/server/rpc-server/sensitive.d.ts +0 -6
  261. package/dist/server/rpc-server/sensitive.d.ts.map +0 -1
  262. package/dist/server/rpc-server/sensitive.js +0 -78
  263. package/dist/server/rpc-server/sensitive.js.map +0 -1
  264. package/dist/server/rpc-server/session.d.ts +0 -39
  265. package/dist/server/rpc-server/session.d.ts.map +0 -1
  266. package/dist/server/rpc-server/session.js +0 -73
  267. package/dist/server/rpc-server/session.js.map +0 -1
  268. package/dist/server/rpc-server/sessionKeys.d.ts +0 -10
  269. package/dist/server/rpc-server/sessionKeys.d.ts.map +0 -1
  270. package/dist/server/rpc-server/sessionKeys.js +0 -22
  271. package/dist/server/rpc-server/sessionKeys.js.map +0 -1
  272. package/dist/server/rpc-server/sessionProfile.d.ts +0 -3
  273. package/dist/server/rpc-server/sessionProfile.d.ts.map +0 -1
  274. package/dist/server/rpc-server/sessionProfile.js +0 -4
  275. package/dist/server/rpc-server/sessionProfile.js.map +0 -1
  276. package/dist/server/rpc-server/tracing.d.ts +0 -9
  277. package/dist/server/rpc-server/tracing.d.ts.map +0 -1
  278. package/dist/server/rpc-server/tracing.js +0 -51
  279. package/dist/server/rpc-server/tracing.js.map +0 -1
  280. package/dist/server/rpc-server/transportHeaders.d.ts +0 -4
  281. package/dist/server/rpc-server/transportHeaders.d.ts.map +0 -1
  282. package/dist/server/rpc-server/transportHeaders.js +0 -6
  283. package/dist/server/rpc-server/transportHeaders.js.map +0 -1
  284. package/dist/server/rpc-server/trustedProxy.d.ts +0 -7
  285. package/dist/server/rpc-server/trustedProxy.d.ts.map +0 -1
  286. package/dist/server/rpc-server/trustedProxy.js +0 -19
  287. package/dist/server/rpc-server/trustedProxy.js.map +0 -1
  288. package/dist/server/rpc-server/trustedProxyRanges.d.ts +0 -2
  289. package/dist/server/rpc-server/trustedProxyRanges.d.ts.map +0 -1
  290. package/dist/server/rpc-server/trustedProxyRanges.js +0 -5
  291. package/dist/server/rpc-server/trustedProxyRanges.js.map +0 -1
  292. package/dist/server/runtime/makePlatform.d.ts +0 -4
  293. package/dist/server/runtime/makePlatform.d.ts.map +0 -1
  294. package/dist/server/runtime/makePlatform.js +0 -65
  295. package/dist/server/runtime/makePlatform.js.map +0 -1
  296. package/dist/server/runtime/types.d.ts +0 -19
  297. package/dist/server/runtime/types.d.ts.map +0 -1
  298. package/dist/server/runtime/types.js +0 -2
  299. package/dist/server/runtime/types.js.map +0 -1
  300. package/dist/server/safeOtlpSerialization.d.ts +0 -6
  301. package/dist/server/safeOtlpSerialization.d.ts.map +0 -1
  302. package/dist/server/safeOtlpSerialization.js +0 -67
  303. package/dist/server/safeOtlpSerialization.js.map +0 -1
  304. package/dist/server/schemaSensitiveKeys.d.ts +0 -5
  305. package/dist/server/schemaSensitiveKeys.d.ts.map +0 -1
  306. package/dist/server/schemaSensitiveKeys.js +0 -143
  307. package/dist/server/schemaSensitiveKeys.js.map +0 -1
  308. package/dist/server/setupDatabases.d.ts +0 -3
  309. package/dist/server/setupDatabases.d.ts.map +0 -1
  310. package/dist/server/setupDatabases.js +0 -12
  311. package/dist/server/setupDatabases.js.map +0 -1
  312. package/dist/server/testing/makePlatformIt.d.ts +0 -8
  313. package/dist/server/testing/makePlatformIt.d.ts.map +0 -1
  314. package/dist/server/testing/makePlatformIt.js +0 -32
  315. package/dist/server/testing/makePlatformIt.js.map +0 -1
  316. package/dist/server/testing/types.d.ts +0 -28
  317. package/dist/server/testing/types.d.ts.map +0 -1
  318. package/dist/server/testing/types.js +0 -2
  319. package/dist/server/testing/types.js.map +0 -1
  320. package/dist/server/tracedGroup.d.ts +0 -4
  321. package/dist/server/tracedGroup.d.ts.map +0 -1
  322. package/dist/server/tracedGroup.js +0 -13
  323. package/dist/server/tracedGroup.js.map +0 -1
  324. package/src/http-client/body.ts +0 -37
  325. package/src/http-client/errors.ts +0 -23
  326. package/src/http-client/filterStatus.ts +0 -38
  327. package/src/http-client/nextLink.ts +0 -10
  328. package/src/http-client/paginate.ts +0 -39
  329. package/src/http-client/parseRetryAfter.ts +0 -17
  330. package/src/rpc/identity.ts +0 -26
  331. package/src/rpc/middleware.ts +0 -38
  332. package/src/rpc/permission.ts +0 -24
  333. package/src/rpc/publicConfig.ts +0 -9
  334. package/src/rpc/userRoles.ts +0 -23
  335. package/src/server/AppHostFactory.ts +0 -121
  336. package/src/server/AppHostInput.ts +0 -74
  337. package/src/server/MigrationOptions.ts +0 -15
  338. package/src/server/RedactionPolicy.ts +0 -4
  339. package/src/server/appHost.ts +0 -117
  340. package/src/server/appHostHttp.ts +0 -147
  341. package/src/server/better-auth/adapter.ts +0 -81
  342. package/src/server/better-auth/allowedAccounts.ts +0 -29
  343. package/src/server/better-auth/bearerSessions.ts +0 -50
  344. package/src/server/better-auth/memoryRateLimit.ts +0 -56
  345. package/src/server/better-auth/mount.ts +0 -145
  346. package/src/server/better-auth/mountRoutes.ts +0 -75
  347. package/src/server/better-auth/mountedSessions.ts +0 -21
  348. package/src/server/better-auth/relation.ts +0 -59
  349. package/src/server/better-auth/revokeUnadmitted.ts +0 -41
  350. package/src/server/better-auth/rowAdapter.ts +0 -78
  351. package/src/server/better-auth/sessionPermissions.ts +0 -18
  352. package/src/server/better-auth/signInGate.ts +0 -77
  353. package/src/server/better-auth/signInPolicy.ts +0 -72
  354. package/src/server/better-auth/testDatabase.ts +0 -27
  355. package/src/server/better-auth/testing.ts +0 -35
  356. package/src/server/better-auth/userProfiles.ts +0 -37
  357. package/src/server/better-auth/users.ts +0 -67
  358. package/src/server/better-auth/where.ts +0 -123
  359. package/src/server/boundedBody.ts +0 -45
  360. package/src/server/boundedRpcRequest.ts +0 -28
  361. package/src/server/commandChanges.ts +0 -52
  362. package/src/server/databaseAddress.ts +0 -25
  363. package/src/server/databaseLayer.ts +0 -127
  364. package/src/server/development.ts +0 -34
  365. package/src/server/healthRoute.ts +0 -27
  366. package/src/server/hostChanges.ts +0 -34
  367. package/src/server/hostOptions.ts +0 -30
  368. package/src/server/hostTransport.ts +0 -26
  369. package/src/server/nativeClientOrigins.ts +0 -44
  370. package/src/server/node-http/subscriptionSignal.ts +0 -64
  371. package/src/server/otlpHttpClient.ts +0 -54
  372. package/src/server/otlpTracing.ts +0 -61
  373. package/src/server/redactOtlpUrl.ts +0 -48
  374. package/src/server/redactingDiagnostics.ts +0 -33
  375. package/src/server/redactingRpcSerialization.ts +0 -85
  376. package/src/server/redactingTracer.ts +0 -37
  377. package/src/server/rpc-server/adapters/betterAuthSessions.ts +0 -44
  378. package/src/server/rpc-server/boundary.ts +0 -26
  379. package/src/server/rpc-server/local.ts +0 -100
  380. package/src/server/rpc-server/origin.ts +0 -26
  381. package/src/server/rpc-server/permissions.ts +0 -51
  382. package/src/server/rpc-server/proxyRanges.ts +0 -61
  383. package/src/server/rpc-server/publicConfigLayer.ts +0 -12
  384. package/src/server/rpc-server/redact.ts +0 -64
  385. package/src/server/rpc-server/redactCause.ts +0 -104
  386. package/src/server/rpc-server/resolveRole.ts +0 -7
  387. package/src/server/rpc-server/revalidateStream.ts +0 -25
  388. package/src/server/rpc-server/sensitive.ts +0 -79
  389. package/src/server/rpc-server/session.ts +0 -148
  390. package/src/server/rpc-server/sessionKeys.ts +0 -25
  391. package/src/server/rpc-server/sessionProfile.ts +0 -5
  392. package/src/server/rpc-server/tracing.ts +0 -68
  393. package/src/server/rpc-server/transportHeaders.ts +0 -8
  394. package/src/server/rpc-server/trustedProxy.ts +0 -22
  395. package/src/server/rpc-server/trustedProxyRanges.ts +0 -5
  396. package/src/server/runtime/makePlatform.ts +0 -75
  397. package/src/server/runtime/types.ts +0 -24
  398. package/src/server/safeOtlpSerialization.ts +0 -73
  399. package/src/server/schemaSensitiveKeys.ts +0 -148
  400. package/src/server/setupDatabases.ts +0 -12
  401. package/src/server/testing/makePlatformIt.ts +0 -76
  402. package/src/server/testing/types.ts +0 -38
  403. package/src/server/tracedGroup.ts +0 -14
package/README.md CHANGED
@@ -1,930 +1,58 @@
1
1
  # @shivaedev/platform
2
2
 
3
- Request identity and server boundaries for Effect applications. A feature can say who called it and why it refused, while the application supplies its session policy once. The package also connects Effect services to Promise callers, Node subscriptions and optional Better Auth, Prisma and tRPC integrations.
3
+ The ShivaeDev framework for Effect applications in one dependency. Platform holds no code of its own: it depends on every runtime piece of the framework, and an application imports each piece by its own name.
4
4
 
5
5
  ## Why you want this
6
6
 
7
- Every feature needs the same boundary questions answered: which user made this request, is the session missing or its provider unavailable, and which failures can the caller act on? Writing that glue repeatedly makes it harder to see the feature's own decision:
7
+ An Effect application built on this framework uses a dozen packages that are released and tested together. Listing them one by one and keeping their versions aligned is busywork that drifts. Depend on platform instead and import what you need from the piece that owns it:
8
8
 
9
9
  ```ts
10
- const Handlers = Account.toLayer({
11
- ReadOwn: ({ userId }) =>
12
- Effect.gen(function* () {
13
- const identity = yield* Identity;
14
- if (identity.id !== userId) {
15
- return yield* new Forbidden({ message: "Not your account" });
16
- }
17
- return identity.id;
18
- }),
19
- });
10
+ import { appHost } from "@shivaedev/server/appHost.ts";
11
+ import { Authenticated } from "@shivaedev/identity/middleware.ts";
12
+ import { NotFound } from "@shivaedev/errors/taxonomy.ts";
20
13
  ```
21
14
 
22
- `Account` is a native RPC group with authenticated middleware. Its handler reads the identity for this invocation and decides whether that user may read the account. Effect Contract supplies the common error classes, and Platform supplies request services; feature code keeps the resource-ownership check. Concurrent requests receive their own identities, and a provider outage reaches the caller as `AuthUnavailable` instead of pretending the caller signed out.
23
-
24
15
  ## Using it
25
16
 
26
- ### How to think about it
27
-
28
- There are three parts to a native RPC boundary:
29
-
30
- 1. **The shared contract** names Schema errors and middleware tags. The browser imports these declarations too, so `effect-contract/errors/` and Platform's `rpc/` contain browser-safe data and services.
31
- 2. **The server composition** implements the tags with Layers from `rpc-server/`. A session provider resolves a session; an Origin policy decides whether its request may reach that provider; tracing supplies a request id and diagnostic context.
32
- 3. **The feature handler** reads `Identity`, `OptionalIdentity` or `RequestId` and runs application code. Authentication supplies a user id. Authorization still decides whether that user may perform this operation.
33
-
34
- An **Origin policy** is a function of the transport request's origin, headers and RPC name. A **session provider** returns `Option<Session>` or fails with `AuthUnavailable`; a session carries `user.id`. These are application inputs, not a second authentication framework.
35
-
36
- The optional modules solve different boundaries. `server/runtime/` carries Effect services into Promise callers, `server/node-http/` combines subscription cancellation sources, `server/better-auth/adapter.ts` connects Better Auth storage to Effect Prisma, and `server/testing/makePlatformIt.ts` composes the Prisma and tRPC test harnesses. Choose the modules that match the application rather than adopting every integration.
37
-
38
- ### Prepare local development
39
-
40
- `setupDatabases()` from `@shivaedev/platform/server/setupDatabases.ts` reads `DATABASE_URL` and `TEST_DATABASE_URL` through Effect Config and prepares both local databases with `@shivaedev/local-postgres`. Database names come from those URLs. `DOCKER_HOST` and `DOCKER_CONTEXT` are optional. Missing database URLs fail with a typed Config error; migrations remain the application's responsibility.
41
-
42
- `development({ server, worker, conditions? })` from `@shivaedev/platform/server/development.ts` starts the two application entry points with Node's watch mode and runs `pnpm exec vite`. Supply paths relative to the application directory and any export conditions its code needs. Provide `NodeServices.layer` to run it. When a process exits, the other processes stop and the Effect returns the first exit code, which the entry point can assign to `process.exitCode`. Use `runDevelopment(options)` from the same module for the Node entry point with that runtime wiring included.
43
-
44
- ### Host the application
45
-
46
- `appHost` is the server entry point for an Effect app. For a PostgreSQL app, supply the native RPC group, handler and service Layers, migration loader, session policy and static asset directory. The host completes migrations before acquiring application services, starts Node HTTP with NDJSON RPC at `/rpc`, and provides SQL, Reactivity and `AppChanges` to those Layers.
47
-
48
- ```ts
49
- import { NodeRuntime } from "@effect/platform-node";
50
- import { Layer } from "effect";
51
- import { appHost } from "@shivaedev/platform/server/appHost.ts";
52
- import { Api, Handlers, Services, migrations, sessions } from "./app.ts";
53
-
54
- const Server = appHost({
55
- group: Api,
56
- handlers: Handlers,
57
- services: Services,
58
- migrations: { loader: migrations },
59
- sessions,
60
- assets: "./public",
61
- });
62
-
63
- NodeRuntime.runMain(Layer.launch(Server));
64
- ```
65
-
66
- `app.ts` exports the application's contracts, native Layers, numbered `Migrator.Loader` and `SessionPolicy`. The host needs the optional peers `@effect/platform-node` and `@effect/sql-pg` at the workspace's Effect version; install both for this entry point. The `node-http/`, `rpc/`, `rpc-server/` and `runtime/` entries still work without them.
67
-
68
- Omit `services` when the app has no service Layer of its own. The host uses `Layer.empty`; handler requirements remain explicit, and a migrated host still provides its database services to handlers. Annotated options that declare service outputs, errors or requirements must supply a `services` Layer.
69
-
70
- `assets` accepts a directory string or native `HttpStaticServer.layer` options. For a browser app whose routes must also work on direct navigation or reload, use `{ root: "dist", spa: true }` or merge `HttpStaticServer.layer({ root: "dist", spa: true })` from `effect/http` alongside the handler Layer. Native route Layers can register additional endpoints in that same composition; `routes` also accepts a native `Layer<never, never, HttpRouter>` for endpoints on the same listener. The [starter](https://github.com/ShivaeDev/platform/tree/main/examples/starter) uses it for static assets and Better Auth at `/api/auth/*`, with provider-owned cookies and the host's RPC session middleware.
71
-
72
- The listener uses `HOST` or `127.0.0.1`, uses `PORT` or 3000, and reads `DATABASE_URL`. Set overrides in the one `config` object: `host`, `port` (0 selects an ephemeral port), `trustedProxy`, `maxBodySize`, `databaseUrl` (an Effect `Redacted<string>`), `applicationName`, and optional `changes`. Migration options accept `table` and `lockTimeout` (default `effect_sql_migrations` and five seconds). Native Layer failures remain in the build error channel; missing application dependencies remain in the requirement type.
73
-
74
- RPC request bodies are limited to 1 MiB by default. Set `MAX_BODY_SIZE` to a byte count or override it with `config.maxBodySize`, a nonnegative safe integer. An oversized NDJSON body, fixed-length or chunked, returns a 4xx before any RPC handler runs. This limit applies to the host's RPC route.
75
-
76
- For a native Node HTTP route, use `readBoundedBody` from `@shivaedev/platform/server/boundedBody.ts` with Effect's `HttpIncomingMessage.MaxBodySize`. It returns an `ArrayBuffer` without decoding the bytes. Oversized `content-length` headers are rejected before reading; chunked overflow drains the remaining body and preserves the connection for another request. `RequestBodyTooLarge` is a typed failure that implements Effect's `HttpServerRespondable` protocol with status 413; other read errors remain native `HttpServerError` failures. Consume the body once through this reader and decode the result in the application.
77
-
78
- ```ts
79
- import { ByteSize, Effect } from "effect";
80
- import { HttpIncomingMessage, HttpRouter, HttpServerResponse } from "effect/http";
81
- import { readBoundedBody } from "@shivaedev/platform/server/boundedBody.ts";
82
-
83
- const routes = HttpRouter.add("POST", "/webhook", (request) =>
84
- readBoundedBody(request).pipe(
85
- Effect.map((body) => HttpServerResponse.uint8Array(new Uint8Array(body))),
86
- Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(64 * 1024)),
87
- ),
88
- );
89
- ```
90
-
91
- RPC uses the existing `localRpcGuard`: it requires a loopback peer and Host, same-origin or absent Origin, and the NDJSON content type. Session lookup uses transport headers. The host applies `RequestTracing` last to every served RPC, including loopback RPC, so it wraps authentication and handlers without a per-contract tracing declaration. Existing tracing declarations run once at that outermost boundary. With a session policy, contracts declare `Authenticated` and `MaybeAuthenticated` as needed; the host supplies their implementations. For `AuthenticatedUser`, merge `authenticatedUserLayer(sessions)` beside the handlers as shown below. Declared errors retain their Schema types. Applications still own resource authorization and use `rpcBoundary` when they need to map unexpected failures.
92
-
93
- Every response from the host's native RPC endpoint carries `Cache-Control: private, no-store`, including mixed public and authenticated batches, typed failures, transport rejections, body-read failures and streams. The host sets this at the outer response boundary without inspecting batch contents.
94
-
95
- For local tools, use `policy: "loopback"` with contracts that do not use session middleware to serve RPC without a session provider. The same guard applies. This policy does not use `TRUSTED_PROXY` or `config.trustedProxy`. Set `rpcPath` to choose another native RPC route; `/rpc` remains the default.
96
-
97
- Omit `migrations` to host an app without a database. This form creates no SQL pool and reads no `DATABASE_URL`; `AppHttpHostOptions` describes it. `AppHostOptions` requires migrations for database-backed hosts. A service that needs SQL still requires a SQL Layer. Provide `appDatabase` to the application’s service Layer when it owns database composition.
98
-
99
- `appHost` serves unauthenticated `GET /health`. It queries its SQL client on each request and returns `200` only when the query succeeds within two seconds; a missing SQL client, query failure or timeout returns `503`. Both responses have an empty body and `Cache-Control: no-store`. This route also works when the SQL client comes from the application’s `services` Layer. Use it for database readiness checks.
100
-
101
- Set `migrations.mode: "check"` on `appDatabase` or a database-backed `appHost` when a separate pre-deploy command owns migrations. Startup reads the ledger and fails with native `MigrationError` (`kind: "BadState"`) if any required migration ID or name is missing or a schema component is pending; it does not run migrations or create a ledger. Later ledger entries are allowed for rolling deployments. Use `migrations.mode: "wait"` for services that can start before that pre-deploy command finishes. It re-reads the ledger and every registered component every second until all are current, then starts the application. Set `migrations.pollInterval` and `migrations.waitTimeout` with Effect duration inputs to change the interval and five-minute timeout. If the first check finds pending work, Effect’s logger emits `Waiting for database migrations` at info, then `Still waiting for database migrations` every 30 seconds independently of polling. Set `migrations.progressInterval` with an Effect duration input to change that progress interval. These lines carry `pendingMigrations` (ID and name) and `pendingComponents` (name and detail) annotations. A later successful check logs `Database migrations current` once; timeout logs `Timed out waiting for database migrations` with the pending annotations before failing. An initially current schema emits none of these lines. The host adds no connection details or secrets to these diagnostics. Timeout fails with the same `MigrationError` as `"check"`; interruption stops polling and closes the pool. SQL failures fail immediately. With `mode` omitted or `"migrate"`, startup applies pending ledger migrations with a five-second lock timeout unless `migrations.lockTimeout` overrides it, then applies schema components outside the ledger transaction.
102
-
103
- Pass `migrations.components` beside `loader` for storage managed by another engine. For pg-boss, register `pgBossSchema({ schema: "app_jobs" })` from `@shivaedev/effect-pg-boss/server/schema.ts`, then start every jobs Layer with `migrate: false`. `check` and `wait` use the same `MigrationError` readout for pending ledger IDs and component names and details, including pg-boss’s installed and required versions.
104
-
105
- Supply `preflight: AppConfigLive` to `appHost` to build a native Layer before checking or applying migrations, or constructing the application. Use it to validate configuration such as app IDs, keys and invite lists. Its errors stay in the returned Layer's typed error channel, its requirements remain external requirements, and its services are available to migrations, application construction, services and RPC handlers as well as callers of the host Layer. Preflight resources close with the host scope. The option also works without migrations.
106
-
107
- When construction itself touches the schema, use `appHost({ migrations, config, application })`. `application` is a native Effect that returns the HTTP host options (`group`, handler and service Layers, session policy, and optional HTTP config). The host first builds `appDatabase`, then evaluates this Effect in the host scope with SQL, Reactivity and `AppChanges` available. A failed migration or schema-current check prevents construction. Initialization requirements and errors stay in the returned Layer's types, and acquired resources close with the host scope.
108
-
109
- ```ts
110
- const host = appHost({
111
- config: { databaseUrl },
112
- migrations: { loader: migrations, mode: "check" },
113
- preflight: AppConfigLive,
114
- application: Effect.gen(function* () {
115
- const { routes, sessions } = yield* makeAuth();
116
- return { group: Api, handlers: Handlers, services: Services, routes, sessions };
117
- }),
118
- });
119
- ```
120
-
121
- Construct Better Auth inside `application`, since its constructor starts schema validation. Keep validation enabled so a current migration ledger with missing auth columns still reports drift. The starter uses this form after its pre-deploy migrations.
122
-
123
- Set `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` to export `appHost`'s Effect spans over OTLP/HTTP. Without an endpoint, no exporter or export loop is built, even when service metadata is set. The `http/protobuf` default follows the [OpenTelemetry recommendation](https://opentelemetry.io/docs/specs/otel/protocol/exporter/#specify-protocol); unsupported protocols, including `grpc`, fail startup with a `ConfigError` naming the value. Header and resource-attribute values are `key=value` pairs with URL-encoded values. Configuration is read through Effect Config.
124
-
125
- The supported tracing variables and defaults are:
126
-
127
- | Variable | Default | Meaning |
128
- | --- | --- | --- |
129
- | `OTEL_EXPORTER_OTLP_ENDPOINT` | Unset | Collector base URL. |
130
- | `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Base URL plus `/v1/traces` | Complete traces URL; takes precedence. |
131
- | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` | `http/protobuf` or `http/json`. |
132
- | `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | General protocol | Overrides the protocol for traces. |
133
- | `OTEL_EXPORTER_OTLP_HEADERS` | Empty | Comma-separated exporter headers. |
134
- | `OTEL_SERVICE_NAME` | Resource `service.name`, then `unknown_service` | Service name. |
135
- | `OTEL_SERVICE_VERSION` | Resource `service.version`, otherwise unset | Service version. |
136
- | `OTEL_RESOURCE_ATTRIBUTES` | Empty | Comma-separated resource attributes. |
137
- | `OTEL_EXPORTER_OTLP_TIMEOUT` | `10000` ms | Timeout for each HTTP export attempt, including its response body. |
138
- | `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` | General timeout | Overrides the request timeout for traces. |
139
- | `OTEL_BSP_SCHEDULE_DELAY` | `5000` ms | Effect tracer's batch export interval. |
140
- | `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | `1000` spans | Effect tracer's batch-size trigger. |
141
- | `OTEL_BSP_EXPORT_TIMEOUT` | `3000` ms | Effect tracer's shutdown flush bound, capped at the request timeout. |
142
-
143
- Timeouts fail through the HTTP client's typed transport-error channel and use the same warning path as other transport failures. Effect retains its native retry policy; the request timeout applies to each attempt. The batch defaults follow Effect's `OtlpTracer.layer`. Its options cannot express a separate batch-operation deadline or a queue capacity, so `OTEL_BSP_EXPORT_TIMEOUT` controls shutdown only and `OTEL_BSP_MAX_QUEUE_SIZE` is unsupported. Other `OTEL_BSP_*` variables are unsupported.
144
-
145
- On Railway, enable the per-service tracing setting separately for the web service and worker, and leave both exporter endpoint variables unset in your app's configuration. Railway documents that it injects the `OTEL_*` variables, including `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`, only when the app sets no endpoint of its own. The framework exports through Effect's own `effect/observability` OTLP tracer; eBPF auto-instrumentation is outside this path. For a worker, provide `otlpTracing` from `@shivaedev/platform/server/otlpTracing.ts` to its application Layer. It batches ended Effect spans and flushes during scoped shutdown with a three-second bound by default. The first failed export logs a warning with the collector status and redacted response body, or the transport failure kind when no response arrives. Repeated failures stay quiet until a successful export. Collector connection failures and HTTP errors leave requests, jobs and shutdown successful.
146
-
147
- Exported HTTP server spans use `{method} {route}` with `http.route` for matched RPC and router paths, including parameter templates; unmatched requests use the method alone. The production host continues incoming W3C `traceparent` context, including one sent by an edge proxy.
148
-
149
- Both JSON and protobuf export serialization apply sensitive-key and credential-text redaction to span attributes, events, links, error details and resource attributes. Credential text includes JWTs, Bearer/Basic credentials, sensitive assignments including bare `sig=...` anywhere in text (with or without `?`), and complete PEM private-key blocks through their matching END marker, including RSA, EC, OPENSSH and encrypted private keys. Matches become `<redacted>`. `sig` uses the shared sensitive-key policy for attributes and text. URL query values, fragments and user information are also redacted. Exporter headers stay in the collector request, outside the spans. Applications must still avoid placing secrets in span names, free text or custom attributes.
150
-
151
- Set `config.maxConnections` on `appDatabase` or a migrated `appHost` to bound the PostgreSQL pool. The change listener reserves one connection; when transactions hold the remaining connections, another query waits until a transaction releases its connection. A daemon with long-lived RPC streams can use `config.disablePreemptiveShutdown: true` so scope closure interrupts an active HTTP RPC stream and runs its finalizer before host disposal completes, without waiting for Node's preemptive graceful-shutdown timeout. Omitting it keeps Node's native graceful-shutdown default.
152
-
153
- For a deployment behind a proxy, set `HOST=0.0.0.0` and `TRUSTED_PROXY` to a comma-separated list of proxy peer IPs or CIDR ranges (IPv4 or IPv6), or use `config.host` and `config.trustedProxy`. Only matching peers may supply `X-Forwarded-Host` and `X-Forwarded-Proto` (`http` or `https`) for the guard's same-origin check; the proxy must overwrite both headers and preserve Origin. A single authority is required, and comma-separated forwarding chains are refused. IPv4-mapped IPv6 peers match their IPv4 address. Malformed addresses or ranges fail `appHost` startup with a typed `ConfigError`. NDJSON and the application's session Origin policy still apply. See the [deployment quickstart](https://github.com/ShivaeDev/platform/blob/main/docs/framework/quickstart.md#deploy).
154
-
155
- Build application handlers with `Api.application.toLayer(...)` (and `Api.application.of(...)` for an Effect-built handler map), then pass the full `Api` to the host and client. `Api.application` is the native RPC group without the reserved `$changes` stream; the host supplies that handler. The explicit `Api.omit("<namespace>.$changes")` form also works.
156
-
157
- Database-backed hosts enable PostgreSQL change delivery by default and serve each contract's reserved change stream under its middleware. After a command handler succeeds, its declared invalidation keys publish without repeating keys already announced by repository commits. The handler keeps ownership of its transactions and error mapping. `config.changes.channel` overrides the app-derived default, and heartbeat and retry settings remain optional. Use the same application name or channel across web and worker processes. A worker can provide `appDatabase({ migrations, config })` without starting HTTP. See [commit-bound changes](https://github.com/ShivaeDev/platform/blob/main/docs/framework/changes.md) for defaults and limits.
158
-
159
- ### Session-scoped contract keys
160
-
161
- For self-only features, declare `contract("preferences", { keyScope: "session", queries, commands }).middleware(Authenticated)`. `List` and `Item` remain the dependency shapes; the account scope is an additional dimension derived from request-local `Identity.id`. Handlers continue to read their owner from `Identity`, and payloads need no owner field just to key reads or invalidations. Other sessions of that account receive its changes; other accounts receive no invalidation hint for those writes.
162
-
163
- The host's generated `$changes` handler accepts `{ queries: [{ query: "get", payload: { id: "theme" } }] }`, resolves the declared query dependencies during that subscription invocation, and passes the authenticated scope to the change stream. It does not accept physical subscription keys or a caller-selected scope. Missing request-local `Identity` on a session-scoped subscription is a configuration defect, with no unscoped fallback.
164
-
165
- `authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer` and `permissionLayer` run scoped command invalidation inside the authenticated invocation. Successful commands publish their scoped keys after commit and omit keys the handler's transactions already published. A rejected transaction publishes no keys.
166
-
167
- Hosted applications use `Api.application.toLayer(...)` and let `appHost` own `$changes`. When migrating a custom change handler, accept query references and resolve them inside `Stream.unwrap`, after authentication has provided `Identity`:
168
-
169
- ```ts
170
- import { Effect, Stream } from "effect";
171
- import { resolveChanges } from "@shivaedev/platform/server/rpc-server/sessionKeys.ts";
172
-
173
- const changesRpc = Api.requests.get("preferences.$changes")!;
174
- const handlers = Api.toLayer({
175
- "preferences.$changes": ({ queries }) => Stream.unwrap(
176
- Effect.map(resolveChanges(changesRpc, queries), ({ keys, context }) =>
177
- changes.stream(keys, context)
178
- )
179
- ),
180
- "preferences.get": getPreference,
181
- "preferences.save": savePreference,
182
- });
183
- ```
184
-
185
- Here `changes` is the application's `makeLiveServer` service. Keep `resolveChanges` in the invocation; resolving it while building a shared Layer would lose request identity. Pass both returned arguments to `changes.stream`.
186
-
187
- Custom authentication middleware supplies the same boundary by validating the transport session, then wrapping scoped commands with `sessionCommandChanges` before providing `Identity`:
188
-
189
- ```ts
190
- import { Effect, Layer } from "effect";
191
- import { Identity } from "@shivaedev/platform/rpc/identity.ts";
192
- import { sessionCommandChanges } from "@shivaedev/platform/server/commandChanges.ts";
193
-
194
- const authentication = Layer.succeed(MyAuthentication, (effect, { headers, rpc, payload }) =>
195
- Effect.gen(function* () {
196
- const session = yield* requireTransportSession(headers, rpc);
197
- return yield* sessionCommandChanges(effect, rpc, payload).pipe(
198
- Effect.provideService(Identity, { id: session.user.id })
199
- );
200
- })
201
- );
202
- ```
203
-
204
- `MyAuthentication` declares `provides: Identity` and its authentication errors. `requireTransportSession` is the application's session validation; use `transportHeaders` or `resolveSession` to read HTTP or WebSocket transport credentials. The identity comes from that validated session on each invocation. `requestTracingLayer` publishes only unscoped contract invalidations; custom auth middleware must apply `sessionCommandChanges` for scoped commands. If a transaction explicitly announces scoped dependencies, use `invalidationKeys(keys, { scope: identity.id })` with `invalidateOnCommit` inside `transact` so automatic command invalidation can deduplicate the same physical keys.
205
-
206
- ### Public client configuration
207
-
208
- Use one `publicConfig` declaration per application as the one path for server configuration that a client needs. Declare only public fields in a shared Schema; the declaration creates a standard effect-contract query, so applications write no config RPC. Keep private configuration in server modules.
209
-
210
- ```ts
211
- import { Schema } from "effect";
212
- import { publicConfig } from "@shivaedev/platform/rpc/publicConfig.ts";
213
-
214
- export const PublicConfig = publicConfig(
215
- Schema.Struct({ installUrl: Schema.URL }).pipe(
216
- Schema.encodeKeys({ installUrl: "INSTALL_URL" }),
217
- ),
218
- );
219
- ```
220
-
221
- On the server, merge the declaration into the application's group and its generated handler Layer into the handlers:
222
-
223
- ```ts
224
- import { Layer } from "effect";
225
- import { appHost } from "@shivaedev/platform/server/appHost.ts";
226
- import { publicConfigLayer } from "@shivaedev/platform/server/rpc-server/publicConfigLayer.ts";
227
- import { Api, Handlers, sessions } from "./app.ts";
228
- import { PublicConfig } from "./public-config.ts";
229
-
230
- export const Server = appHost({
231
- group: Api.merge(PublicConfig),
232
- handlers: Layer.merge(Handlers, publicConfigLayer(PublicConfig)),
233
- sessions,
234
- });
235
- ```
236
-
237
- `publicConfigLayer` reads `Config.schema` from the host's native ConfigProvider when the handler Layer builds. Missing or invalid required fields fail startup with a typed `ConfigError`. An optional second argument supplies a native Config path: `publicConfigLayer(PublicConfig, "PUBLIC")` reads `PUBLIC_INSTALL_URL` with the default environment provider. Only schema-declared fields are loaded and serialized; other server values never enter this response. The generated query has no session middleware, so it can supply public configuration before sign-in. Merge it alongside authenticated contracts rather than applying authentication to the merged group.
238
-
239
- On the client, use the same native `AtomRpc.Service`, NDJSON HTTP protocol and effect-contract `bind` as other queries:
240
-
241
- ```ts
242
- import { Layer } from "effect";
243
- import { FetchHttpClient } from "effect/http";
244
- import * as AtomRpc from "effect/reactivity/AtomRpc";
245
- import { RpcClient, RpcSerialization } from "effect/rpc";
246
- import { bind } from "@shivaedev/effect-contract/bind.ts";
247
- import { useQuery } from "@shivaedev/effect-react/client/resultState.ts";
248
- import { PublicConfig } from "./public-config.ts";
249
-
250
- class ConfigClient extends AtomRpc.Service<ConfigClient>()("app/ConfigClient", {
251
- group: PublicConfig,
252
- protocol: RpcClient.layerProtocolHttp({ url: "/rpc" }).pipe(
253
- Layer.provide([FetchHttpClient.layer, RpcSerialization.layerNdjson]),
254
- ),
255
- }) {}
256
- const config = bind(PublicConfig, ConfigClient);
257
-
258
- export function usePublicConfig() {
259
- return useQuery(config.get.query());
260
- }
261
- ```
262
-
263
- Render inside the application's native registry provider. The query's `data` is an `Option<{ readonly installUrl: URL }>`: the same codec validates server configuration and decodes the RPC response on the client. Public configuration uses the existing atom registry and query lifecycle.
264
-
265
- ### 1. Once per application: contracts and session policy
266
-
267
- Declare the RPC group in a shared module:
268
-
269
- ```ts
270
- import { Effect, Schema } from "effect";
271
- import { Rpc, RpcGroup } from "effect/rpc";
272
- import { Forbidden } from "@shivaedev/effect-contract/errors/taxonomy.ts";
273
- import { Identity } from "@shivaedev/platform/rpc/identity.ts";
274
- import { Authenticated } from "@shivaedev/platform/rpc/middleware.ts";
275
-
276
- export const Account = RpcGroup.make(
277
- Rpc.make("ReadOwn", {
278
- error: Forbidden,
279
- payload: { userId: Schema.String },
280
- success: Schema.String,
281
- }),
282
- ).middleware(Authenticated);
283
-
284
- export const Handlers = Account.toLayer({
285
- ReadOwn: ({ userId }) =>
286
- Effect.gen(function* () {
287
- const identity = yield* Identity;
288
- if (identity.id !== userId) {
289
- return yield* new Forbidden({ message: "Not your account" });
290
- }
291
- return identity.id;
292
- }),
293
- });
294
- ```
295
-
296
- The middleware declaration makes `Identity` available to guarded handlers and adds `Unauthorized`, `AuthUnavailable` and `Forbidden` to the client's failure type. An unguarded handler that requires `Identity` cannot become a service-free handler Layer. Keep the group declaration in the shared module and the handler implementation on the server when organizing application files.
297
-
298
- Supply a provider and an explicit Origin policy as the host's `sessions` input. For a Better Auth provider, adapt its existing session lookup:
299
-
300
- ```ts
301
- import { betterAuthSessions } from "@shivaedev/platform/server/rpc-server/adapters/betterAuthSessions.ts";
302
- import { trustedOrigins } from "@shivaedev/platform/server/rpc-server/origin.ts";
303
- import { auth } from "./auth.ts";
304
-
305
- export const sessions = {
306
- origin: trustedOrigins({ allow: ["http://localhost:3000"], missing: "allow" }),
307
- provider: betterAuthSessions((headers) => auth.api.getSession({ headers })),
308
- };
309
- ```
310
-
311
- `trustedOrigins({ allow, missing })` accepts an exact allowlist and supports `missing: "reject"` or `"allow"`; a custom `OriginPolicy` can decide from the RPC name or transport headers. A denied policy fails with `Forbidden` before provider lookup. The host's HTTP guard also checks Origin against the local request's Host.
312
-
313
- The application's `auth` owns its storage and session configuration. A null lookup becomes a missing session. A thrown or rejected lookup is logged in redacted form and fails with the generic `AuthUnavailable` message. It remains a failure even on an RPC with optional authentication.
314
-
315
- ### Reading other users' public profiles
316
-
317
- Use `userProfiles(auth, userIds)` in server code to display the names of users who made changes. Pass the `auth` instance returned by `betterAuthMount` and a list of user IDs.
318
-
319
- ```ts
320
- import { userProfiles } from "@shivaedev/platform/server/better-auth/userProfiles.ts";
321
-
322
- const profiles = yield* userProfiles(auth, changedByUserIds);
323
- ```
324
-
325
- The Effect returns an array of `{ id, name, image }`, with `image: null` when unset and unknown IDs omitted. It reads duplicate IDs once in one storage query through Better Auth's adapter, honoring the application's model and field mappings. An empty list returns an empty array without querying storage. Each lookup reads the current profile, including names changed through Better Auth. The result never includes email, role, session or account data. A storage failure logs its cause in redacted form and fails with a generic `AuthUnavailable`, without exposing provider exception details to the caller.
326
-
327
- ### Reading the signed-in user
328
-
329
- When a handler needs the current user's name and email, declare `AuthenticatedUser` and read `SessionUser`. `Identity` keeps its `{ id }` shape; the new middleware supplies both services for that invocation. Its provider must return `user: { id, name, email }`, described by `UserSessionShape`.
330
-
331
- ```ts
332
- import { Effect, Layer, Schema } from "effect";
333
- import { Rpc, RpcGroup } from "effect/rpc";
334
- import { SessionUser } from "@shivaedev/platform/rpc/identity.ts";
335
- import { AuthenticatedUser } from "@shivaedev/platform/rpc/middleware.ts";
336
- import { authenticatedUserLayer } from "@shivaedev/platform/server/rpc-server/session.ts";
337
-
338
- export const Account = RpcGroup.make(
339
- Rpc.make("Whoami", {
340
- success: Schema.Struct({ id: Schema.String, name: Schema.String, email: Schema.String }),
341
- }),
342
- ).middleware(AuthenticatedUser);
17
+ ### How the shell works
343
18
 
344
- export const AccountHandlers = Account.toLayer({
345
- Whoami: () => Effect.map(SessionUser, (user) => user),
346
- });
19
+ Platform is a dependency shell. Its manifest lists every runtime piece at the versions released together, and it exports nothing but its `package.json`. An application never imports `@shivaedev/platform/...`; it imports a module from the piece that owns it, by that piece's name, exactly as a library does. One upgrade of platform moves every piece at once.
347
20
 
348
- export const AccountServer = Layer.merge(AccountHandlers, authenticatedUserLayer(sessions));
349
- ```
350
-
351
- Here `sessions` is the application's policy from the previous example, with a Better Auth lookup that returns all three user fields. Merge `authenticatedUserLayer(sessions)` alongside the handler Layer when using `appHost`; the host continues to supply its id-only and optional middleware. A missing session fails with typed `Unauthorized`; rejected origins fail with `Forbidden`, and provider failures remain `AuthUnavailable`. The profile contains id, name and email, plus an optional role when the provider supplies it, without exposing the rest of the provider's user record. Handlers do not query the provider's user table.
352
-
353
- #### Reading provider account IDs
21
+ pnpm installs a dependency's dependencies out of an application's reach unless the application hoists them, so an application on platform hoists the `@shivaedev` scope. Without that setting the pieces are installed, but type checking cannot resolve an import of any piece the application does not list itself.
354
22
 
355
- Pass Better Auth's account lookup as the second argument to `betterAuthSessions`. Declare `AuthenticatedUserWithProviderAccounts` on account-reading RPCs and merge `authenticatedUserWithProviderAccountsLayer(sessions)` alongside their handlers. This boundary requires a provider whose user has a `providerAccounts` Effect; a provider without the second lookup does not satisfy that type.
356
-
357
- ```ts
358
- import { SessionUserWithProviderAccounts } from "@shivaedev/platform/rpc/identity.ts";
359
- import { AuthenticatedUserWithProviderAccounts } from "@shivaedev/platform/rpc/middleware.ts";
360
- import { AuthUnavailable, Unauthorized } from "@shivaedev/effect-contract/errors/taxonomy.ts";
361
- import { authenticatedUserWithProviderAccountsLayer } from "@shivaedev/platform/server/rpc-server/session.ts";
23
+ ### Set up an application
362
24
 
363
- const sessions = {
364
- origin: trustedOrigins({ allow: ["https://app.example"], missing: "reject" }),
365
- provider: betterAuthSessions(
366
- (headers) => auth.api.getSession({ headers }),
367
- (headers) => auth.api.listUserAccounts({ headers }),
368
- ),
369
- };
25
+ Add `@shivaedev/platform` to `dependencies`, add `@shivaedev/test-story` and `@shivaedev/quality` to `devDependencies`, and hoist the scope in `pnpm-workspace.yaml`:
370
26
 
371
- const githubAccount = Effect.gen(function* () {
372
- const user = yield* SessionUserWithProviderAccounts;
373
- const accounts = yield* user.providerAccounts;
374
- return accounts.find((account) => account.providerId === "github");
375
- });
27
+ ```yaml
28
+ publicHoistPattern: ["@shivaedev/*"]
376
29
  ```
377
30
 
378
- Declare `Schema.Union([AuthUnavailable, Unauthorized])` in the account-reading RPC's `error` schema: lookup failures now come from the handler's Effect. An outage fails with `AuthUnavailable`; a session that expires before the lookup fails with `Unauthorized`. Neither failure exposes provider exception details.
379
-
380
- The lookup uses the same transport headers and runs only when the handler evaluates `user.providerAccounts`. The boundary memoizes a successful result in that invocation's Effect context, including concurrent reads, without sharing it across requests or users. A failed lookup is not retained: the next read tries again. Identity-only handlers never run the accounts lookup. `SessionUserWithProviderAccountsValue.providerAccounts` is a required `Effect<readonly ProviderAccountValue[], AuthUnavailable | Unauthorized>`. Each result contains only `{ providerId: string, accountId: string }`; for example, GitHub's numeric user ID is the string `"123"`, not Better Auth's account-row id. `SessionUser` and `SessionUserValue` contain the base profile without accounts.
381
-
382
- A custom session provider supplies `user.providerAccounts` as a lazy Effect with that same result and failure type, described by `ProviderAccountsSessionShape`. The boundary owns request-local memoization and the reduction to public IDs; custom providers need not cache or project the returned account objects.
383
-
384
- ### Session freshness in streams
385
-
386
- `authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, the role layers and signed-in `maybeAuthenticatedLayer` calls revalidate live RPC streams every 30 seconds by default, using the original transport headers. A missing or revoked session ends the stream with `Unauthorized`, including an idle stream. With a session store that reflects sign-out immediately, delivery can continue for up to that interval plus the session lookup time after sign-out. Provider cookie caching or secondary storage can add their own delay; keep Better Auth's cookie cache disabled for database-backed revocation.
387
-
388
- Set `SessionPolicy.streamRevalidationInterval` to an Effect `Duration.Input` to change the interval for middleware using that policy:
389
-
390
- ```ts
391
- const sessions = {
392
- origin: trustedOrigins({ allow: ["https://app.example.com"], missing: "reject" }),
393
- provider: betterAuthSessions((headers) => auth.api.getSession({ headers })),
394
- streamRevalidationInterval: "5 seconds",
395
- };
396
- ```
397
-
398
- An `AuthUnavailable` failure during revalidation leaves the stream running and the next interval checks again. During a session-store outage, the sign-out delivery window extends until a lookup succeeds. Initial session lookup failures still reject the subscription. Unary calls resolve their session once per call. `MaybeAuthenticated` streams that start anonymous continue without a session monitor; a signed-in optional stream ends with `Unauthorized` when its session is removed. Callers can subscribe again to continue anonymously.
399
-
400
- ### Requiring a permission
401
-
402
- Declare application roles with `@shivaedev/access`. Each user row stores one declared role string. Supply the role set once through the existing auth configuration and reuse its returned session policy:
403
-
404
- ```ts
405
- import { permission } from "@shivaedev/access/permission.ts";
406
- import { role } from "@shivaedev/access/role.ts";
407
- import { roleSet } from "@shivaedev/access/roleSet.ts";
408
- import { betterAuthMount } from "@shivaedev/platform/server/better-auth/mount.ts";
409
-
410
- const UseTools = permission("tools.use");
411
- const Access = roleSet(role("member", []), role("operator", [UseTools]));
412
- const mounted = yield* betterAuthMount(authOptions, { roles: Access });
413
- const sessions = { ...mounted.sessions, origin: trustedOrigins({ allow: ["https://app.example.com"], missing: "reject" }) };
414
- ```
415
-
416
- For another session provider, put `roles: Access` alongside `provider` and `origin` in the host's existing `sessions` policy. The provider must read the current stored role on every invocation. `betterAuthMount`'s returned provider and its existing `/api/auth/get-session` endpoint bypass the cookie cache. That endpoint adds `user.permissions`, an array of `{ name, strength }` grants, and the request-local `SessionUser` exposes the same decoded role and grants. An undeclared stored role fails with `AuthUnavailable` instead of silently granting an empty role.
417
-
418
- Declare a native middleware service for each required permission and provide its Layer beside the handlers:
419
-
420
- ```ts
421
- import { Effect, Layer, Schema } from "effect";
422
- import { Rpc, RpcGroup } from "effect/rpc";
423
- import { SessionUser } from "@shivaedev/platform/rpc/identity.ts";
424
- import { permissionMiddleware } from "@shivaedev/platform/rpc/permission.ts";
425
- import { permissionLayer } from "@shivaedev/platform/server/rpc-server/permissions.ts";
426
-
427
- class ToolsPermission extends permissionMiddleware<ToolsPermission>()("app/ToolsPermission", UseTools) {}
428
- const Tools = RpcGroup.make(Rpc.make("tools", { success: Schema.String }).middleware(ToolsPermission));
429
- const handlers = Tools.toLayer({ tools: () => Effect.map(SessionUser, (user) => user.email) }).pipe(
430
- Layer.provideMerge(permissionLayer(ToolsPermission, sessions)),
431
- );
432
- ```
433
-
434
- The middleware resolves and checks the session on every request before invoking the handler. It provides `Identity` and `SessionUser`, rejects signed-out callers with `Unauthorized`, and rejects missing grants with `Forbidden` in its declared error channel. A permission checks an exact name and strength; an `any` grant does not imply the corresponding `own` grant. Open streams recheck their required permission at the session revalidation interval and end with `Forbidden` after its removal.
435
-
436
- For HTTP routes, use `permissionRoute(sessions, UseTools)` around the handler. It uses the same transport session and Origin policy, returns 401 for missing sessions, 403 for missing grants or refused Origins, and 503 for `AuthUnavailable`. Those rejections carry `Cache-Control: private, no-store`. The handler's response and typed failures pass through unchanged.
437
-
438
- ```ts
439
- import { HttpRouter, HttpServerResponse } from "effect/http";
440
- import { permissionRoute } from "@shivaedev/platform/server/rpc-server/permissions.ts";
441
-
442
- const routes = HttpRouter.use((router) =>
443
- router.add("GET", "/tools", permissionRoute(sessions, UseTools)(() =>
444
- Effect.map(SessionUser, (user) => HttpServerResponse.text(user.email)),
445
- )),
446
- );
447
- ```
448
-
449
- An operation on one record reads that record's owner and uses the application's access policy. With a request-local user, `const { role } = yield* Access.resolve(user.role)` recovers the application's closed role type; `yield* Access.requireAccess({ id: user.id, role }, UseTools, record.ownerId)` then permits an explicit `any` grant or an `own` grant for that owner. Keep these resource decisions in the handler or domain service. Browser interfaces can use `hasPermission(user, permission)` from `rpc/permission.ts` over the client session's grants; the server always resolves its own grants.
450
-
451
- ### Transport headers and request ids
452
-
453
- Session resolution reads `HttpServerRequest`: the HTTP POST or WebSocket upgrade request. Credentials and Origin supplied inside an RPC message cannot replace those transport headers. An application-owned middleware can use `transportHeaders(rpcHeaders)` for the same source of headers.
454
-
455
- effect-react’s `actionTrace` groups an action’s RPC Effects under one browser trace; editor saves and create submissions group their save Effects automatically. Native `RpcClient.layerProtocolHttp` with `FetchHttpClient.layer` sends W3C `traceparent` on each request. appHost continues that HTTP trace for RPC handling, including without an installed tracer or exporter. Each RPC span records `request.id` and `rpc.method`; native SQL spans executed by the handler inherit that trace.
456
-
457
- When a handler enqueues through effect-pg-boss, the job stores the current span context. Wrap enqueueing in an application-named producer span with `Effect.withSpan("Receipt.enqueue", { kind: "producer" })` to show the enqueue operation in the action trace. Worker attempts run in their own trace, linked back to the captured sender span. A trace viewer can follow that link between the action and its job.
31
+ The application lists no piece beside platform, and no test piece beside `@shivaedev/test-story`, which brings `@shivaedev/test` and `@shivaedev/test-sql`. Quality checks this: `manifests/application` asks for the hoist setting and names any duplicate entry to remove, and `imports/manifest` and Biome's undeclared-dependency check accept an application's imports of the pieces its entry points bring. `create-app` writes this setup for a new application and `create-app update` brings an existing one to it.
458
32
 
459
- Tracing uses the RPC headers for correlation. `requestTracingLayer()` accepts `x-request-id`; `{ header: "x-correlation-id" }` changes the name. Missing, malformed or oversized values receive generated 32-character lowercase hexadecimal ids. A request id reaches the `RequestId` service, log annotations as `requestId`, and the server span as `request.id`; the RPC method reaches both as `rpc.method`.
33
+ Platform forwards the pieces' peer dependencies as optional peers. Install the ones the pieces you use need, such as `effect`, `react`, `react-dom`, `pg`, `pg-boss` and `better-auth`; the starter lists them.
460
34
 
461
- Caller-chosen request ids are correlation data. Keep authorization tied to the authenticated identity.
35
+ Only applications depend on platform. A library, or an application published for others to run with `pnpm dlx` or a global install, cannot rely on the hoist setting of the workspace that installs it, so it declares each piece it imports directly.
462
36
 
463
- ### 2. Once per feature: identity and typed refusals
37
+ ### Which package owns which job
464
38
 
465
- Use `Authenticated` when the operation needs `Identity`, and `MaybeAuthenticated` with `maybeAuthenticatedLayer(policy)` when it reads `OptionalIdentity`:
466
-
467
- ```ts
468
- import { Effect, Option, Schema } from "effect";
469
- import { Rpc, RpcGroup } from "effect/rpc";
470
- import { OptionalIdentity } from "@shivaedev/platform/rpc/identity.ts";
471
- import { MaybeAuthenticated } from "@shivaedev/platform/rpc/middleware.ts";
472
-
473
- export const Greetings = RpcGroup.make(
474
- Rpc.make("Greeting", { success: Schema.String }),
475
- ).middleware(MaybeAuthenticated);
476
-
477
- export const GreetingHandlers = Greetings.toLayer({
478
- Greeting: () =>
479
- Effect.map(OptionalIdentity, (identity) =>
480
- Option.match(identity, {
481
- onNone: () => "hello anonymous",
482
- onSome: ({ id }) => `hello ${id}`,
483
- }),
484
- ),
485
- });
486
- ```
487
-
488
- A missing session produces `Option.none()` here. The same policy still rejects forbidden origins and distinguishes provider failure from an anonymous caller. Signed-in authenticated requests annotate the user's id on logs as `userId` and spans as `user.id`.
489
-
490
- For an HTTP RPC server that serves only the local machine, wrap its HTTP effect with `localRpcGuard` from `@shivaedev/platform/server/rpc-server/local.ts`. Provide the native `HttpServerRequest` and `RpcSerialization` services around the returned effect, using the same serialization as the RPC server. No session provider is required.
491
-
492
- By default, the guard returns HTTP 403 before running the effect unless the transport reports a loopback peer address, the Host is a loopback host, any Origin matches the HTTP Host, and the content type matches the serialization. An absent peer address is rejected, and a DNS-rebinding Host on a loopback connection is refused. The optional second argument, `localRpcGuard(effect, trustedProxy)`, enables the same address and range forwarding policy as `appHost`.
493
-
494
- The same module exports `loopbackOnly(handler)` for local page routes and `sameOrigin(request)` for an HTTP Origin check. `loopbackOnly` checks Host and any known peer address; it permits an absent peer address so embedded Fetch page handlers remain usable. It does not check Origin or content type.
495
-
496
- `trustedProxyPeer(trustedProxy?)` compiles the guard's proxy address list into an `(address: string) => boolean` predicate. Use it with the transport's remote address when another route needs the same proxy trust decision. It supports the same IP addresses, CIDR ranges and IPv4-mapped IPv6 peers as `appHost`; absent or malformed configuration matches no peer. It does not read forwarded headers.
497
-
498
- `trustedProxyRanges(trustedProxy?)` returns the equivalent IP addresses and CIDR ranges used by that matcher. Mapped IPv6 addresses and CIDRs become IPv4 entries: `::ffff:127.0.0.0/104` becomes `127.0.0.0/8`, including hexadecimal mapped forms. Broader IPv6 ranges retain both native IPv6 and mapped IPv4 coverage. Missing or malformed configuration returns an empty list. Pass these ranges to a forwarded-header integration after checking the transport with `trustedProxyPeer`.
499
-
500
- Declare expected refusals with the shared tagged error schemas from [effect-contract](https://github.com/ShivaeDev/platform/tree/main/packages/effect-contract#expected-failures). They work with native RPC without authentication middleware. For tRPC, use the rejection schema and formatter from [effect-trpc](https://github.com/ShivaeDev/platform/tree/main/packages/effect-trpc); that HTTP boundary owns status mapping.
501
-
502
- ### Handling unexpected failures
503
-
504
- At the handler edge, `rpcBoundary(schema, options)` keeps declared rejections and maps other failures and defects into one declared fallback. It leaves successful values and interruption intact:
505
-
506
- ```ts
507
- import { Schema } from "effect";
508
- import { Conflict, InternalServerError } from "@shivaedev/effect-contract/errors/taxonomy.ts";
509
- import { rpcBoundary } from "@shivaedev/platform/server/rpc-server/boundary.ts";
510
-
511
- const Rejection = Schema.Union([Conflict, InternalServerError]);
512
- const expose = rpcBoundary(Rejection, {
513
- unexpected: (message) => new InternalServerError({ message }),
514
- });
515
-
516
- export const save = storageSave.pipe(expose);
517
- ```
518
-
519
- `storageSave` is the application's Effect. `unexpected` constructs a member of the declared schema from the public message. The default message is `Internal server error`; `message` supplies application text, with credential-shaped strings redacted. The original Effect cause is kept on the server rejection's non-enumerable `cause`, so an RPC server span can trace it. Keep `cause` out of the wire schema, as the taxonomy classes do. `ServiceUnavailable` describes a declared availability failure without implying a session-provider outage.
520
-
521
- ### Request diagnostics
522
-
523
- Tracing logs declared failures with `RPC failure` and their tag, and defects with `RPC defect`. Interrupt-only causes emit `RPC interrupted` at debug instead, with `rpc.method`, `requestId`, the `rpc.duration` log span and the same redacted payload. The RPC trace span carries `rpc.interrupted: true`; Effect exports interruption with an unset span status. Completed and failed RPCs receive no interruption marker. The diagnostic payload masks nested credential-shaped keys and Effect `Redacted` values. Credential-shaped strings, such as bearer tokens, URL passwords and sensitive `key=value` text, are masked too. Strings retain at most 2,048 characters before a truncation marker; collections retain at most 50 entries with a marker for the remainder, and binary values become size summaries.
524
-
525
- `appHost` derives sensitive field names from the served RPC group's payload, success, error, defect and middleware error schemas, including nested schemas. Use `Schema.Redacted(...)`, `Schema.RedactedFromValue(...)`, or annotate a field with `sensitive: true`. The host treats those names as sensitive throughout that app, even when a diagnostic contains an unwrapped value. Add other exact, case-sensitive names once in `config.sensitiveKeys`:
526
-
527
- ```ts
528
- import { Schema } from "effect";
529
-
530
- const Contact = Schema.Struct({
531
- deliveryAddress: Schema.String.annotate({ sensitive: true }),
532
- recoveryCode: Schema.RedactedFromValue(Schema.String),
533
- });
534
-
535
- const Server = appHost({
536
- group: Api,
537
- handlers: Handlers,
538
- sessions,
539
- config: { sensitiveKeys: ["customerReference"] },
540
- });
541
- ```
542
-
543
- Use `Contact` in `Api`'s RPC schemas. A `sensitive: true` annotation also applies to a checked schema, such as `Schema.String.check(Schema.isMinLength(1)).annotate({ sensitive: true })`, and to checks or groups nested inside other check groups. Values under the declared names become `<redacted>` in host log messages and annotations, failure and defect payloads sent to RPC clients, causes passed to installed error reporters, and exported trace attributes, events, links and resource attributes. Nested structured values follow the same policy before trace serialization. A field containing sensitive array items or record values is masked as a whole. `Schema.encodeKeys` and other schema encoders carry sensitivity to their declared output names, including chains of renamed fields. The host collects all sensitive declarations before propagating encoded names and enclosing-field protection until the key set stops growing, so schema and RPC order do not change the policy. Sensitivity is checked throughout each transformation's source subtree, including fields named in `config.sensitiveKeys`. Policy derivation does not execute encoder callbacks: their field provenance is unknown, so every declared output field of a sensitive source is treated as sensitive, including every union branch, otherwise public fields and error discriminators. When a sensitive source encodes to a scalar, its enclosing field is masked as a whole. Sensitive error tags are masked before tracing copies them into the `rpc.failure` log annotation. Native RPC protocol tags remain intact. An `Error` retains its message, stack and cause in redacted form. If `message` or `name` is sensitive, its stack is masked too, including stack headers encoded by `Schema.Defect({ includeStack: true })`. Successful RPC responses retain their application data. Error schemas consumed by native clients must accept the redaction marker for sensitive fields; a constrained string, numeric or collection field may otherwise fail client decoding after masking.
544
-
545
- A sensitive error encoded to a top-level scalar or record has no fixed output field name to mask. The host replaces that entire failure value with `<redacted>`. This decision follows each RPC schema, so other methods' failures and successful results retain their application data. Client wire-error schemas must accept the string marker in place of that error. Wire masking preserves public collection entries, deeply nested values and long text; diagnostic collection, depth and string limits apply to logs and diagnostic copies, not client failure data.
546
-
547
- Diagnostic failure, defect and interruption reasons are rebuilt with sanitized annotations. When `stack` is sensitive, native `Cause.StackTrace` and `Cause.InterruptorStackTrace` annotations are omitted before reporters or trace exporters receive the cause. Other annotations and interruption identities are preserved. Public native stack frames keep callable stack suppliers and valid parent links; a truncated parent chain ends with `undefined` so reporters and trace exporters can still format it.
548
-
549
- The policy matches field names, not arbitrary occurrences of their values in prose. Free text uses only the existing credential-shaped string and key-assignment rules; it does not scan for personal data. Keep sensitive values out of ordinary prose and span names.
550
-
551
- For native RPC serialization, `schemaSensitiveKeys(group, extraKeys?)` returns a key predicate with `maskFailure(tag: string | undefined, reason: "Fail" | "Die")`. Pass both to `redactingRpcSerialization(wire, sensitive, sensitive.maskFailure)`. The serializer correlates request tags and response IDs, including batches, before masking a whole error or defect root. Unassociated defects use the conservative policy across the host's defect schemas.
552
-
553
- `redactWire(value, sensitive?)` applies the same sensitive-key and credential masking without diagnostic summaries or truncation. `redactText(text, sensitive, maxLength?)` keeps its default 2,048-character diagnostic limit; passing `Infinity` keeps complete public text.
554
-
555
- For a native RPC server composed without `appHost`, `requestTracingLayer({ sensitive })` accepts a key predicate; `isSensitiveKey` supplies the default credential rules. `redactingErrorReporter(reporter, sensitive?)` wraps an Effect error reporter and passes it redacted failure and defect causes while preserving reporting hints such as severity and redacted attributes.
556
-
557
- ### Calling outside APIs
558
-
559
- Use Effect's HTTP client with `filterStatus`, `paginate` and the bounded body readers:
560
-
561
- ```ts
562
- import { Effect, Schema, Stream } from "effect";
563
- import { HttpClient, HttpClientRequest } from "effect/http";
564
- import { readBoundedJson } from "@shivaedev/platform/http-client/body.ts";
565
- import { filterStatus } from "@shivaedev/platform/http-client/filterStatus.ts";
566
- import { paginate } from "@shivaedev/platform/http-client/paginate.ts";
567
-
568
- const items = Effect.gen(function* () {
569
- const client = filterStatus(yield* HttpClient.HttpClient);
570
- return yield* paginate(client, HttpClientRequest.get("https://api.example/items")).pipe(
571
- Stream.mapEffect((response) => readBoundedJson(response, 64 * 1024, Schema.Array(Schema.String))),
572
- Stream.runCollect,
573
- Effect.map((pages) => pages.flat()),
574
- );
575
- });
576
- ```
577
-
578
- Provide a native client Layer such as `FetchHttpClient.layer` from `effect/http`. `filterStatus` passes 2xx responses through and fails other statuses with Schema tagged errors from `http-client/errors.ts`: `RemoteUnauthorized` (401), `RemoteNotFound` (404), `RemoteGone` (410), `RemoteRateLimited` (429, or 503 carrying `Retry-After`) and `RemoteHttpError` for other statuses. Errors carry the method, URL without its query string and status, without headers or body. `RemoteRateLimited.retryAfter` is an optional UTC `DateTime`: delay-seconds use Effect's clock, and HTTP dates name the instant directly. Missing or invalid values leave it undefined.
579
-
580
- `paginate` follows quoted or unquoted `rel=next`, including headers with multiple links and relations, resolves relative links and stops at the last page. Taking one page sends one request. A next link on another origin fails with `PaginationLinkError` before that request is sent.
581
-
582
- `readBoundedBody(response, limit)` returns bytes; `readBoundedText` decodes UTF-8, and `readBoundedJson(response, limit, schema)` decodes JSON through the supplied Schema. Limits are bytes. An oversized `Content-Length` fails with `ResponseBodyTooLarge` before reading the body; a chunked body that exceeds the limit fails during the read. The error carries `limit`.
583
-
584
- ### Promise callers: one application runtime
585
-
586
- Build the application Layer once. `runWithServices` supplies an invocation's overrides to subsequent calls on the same runtime, across Promise awaits:
587
-
588
- ```ts
589
- import { Context, Layer } from "effect";
590
- import { makePlatformRuntime } from "@shivaedev/platform/server/runtime/makePlatform.ts";
591
-
592
- class Greeting extends Context.Service<Greeting, string>()("app/Greeting") {}
593
-
594
- const runtime = makePlatformRuntime(Layer.succeed(Greeting, "application"));
595
- const base = await runtime.runPromise(Greeting);
596
- const request = await runtime.runWithServices(
597
- Context.make(Greeting, "request"),
598
- async () => {
599
- await Promise.resolve();
600
- return runtime.runPromise(Greeting);
601
- },
602
- );
603
- await runtime.dispose();
604
- ```
605
-
606
- `base` is `"application"` and `request` is `"request"`. The application's resource Layer is acquired once across calls. An explicit `developmentCacheKey` shares a runtime between calls with that key during development. Each key belongs to one application runtime definition.
607
-
608
- A nested `runWithServices` call replaces the outer invocation's overrides for its callback. Merge the contexts explicitly when the nested call must retain those overrides.
609
-
610
- ### Node subscriptions: combine cancellation and clean up
611
-
612
- A long-lived response can receive cancellation from a Web request, a procedure and its underlying Node connection:
613
-
614
- ```ts
615
- import type { IncomingMessage } from "node:http";
616
- import { nodeSubscriptionSignal } from "@shivaedev/platform/server/node-http/subscriptionSignal.ts";
617
-
618
- export async function consumeSubscription(
619
- request: Request,
620
- nodeRequest: IncomingMessage,
621
- procedureSignal: AbortSignal,
622
- consume: (signal: AbortSignal) => Promise<void>,
623
- ) {
624
- const subscription = nodeSubscriptionSignal({
625
- nodeRequest,
626
- request,
627
- signals: [procedureSignal],
628
- });
629
- try {
630
- await consume(subscription.signal);
631
- } finally {
632
- subscription.dispose();
633
- }
634
- }
635
- ```
636
-
637
- The signal aborts on an additional signal, socket close, incomplete request close or an already destroyed connection. Normal completion of a request does not abort a continuing response. Without an explicit `nodeRequest`, the helper can read one from an srvx Web request's `runtime.node.req`. `dispose()` removes Node listeners and can be called repeatedly.
638
-
639
- ### Mount Better Auth
640
-
641
- `betterAuthMount(options)` returns the Better Auth instance and a native route Layer for `/api/auth/*`. It accepts Better Auth options, including application plugins and session policy. Merge `routes` into the HTTP host and use `auth.api.getSession` with `betterAuthSessions` for the application's RPC session provider.
642
-
643
- ```ts
644
- import { Config, Effect } from "effect";
645
- import { authDatabase, betterAuthMount } from "@shivaedev/platform/server/better-auth/mount.ts";
646
-
647
- const authentication = Effect.gen(function* () {
648
- const database = yield* authDatabase(yield* Config.Redacted("DATABASE_URL"));
649
- return yield* betterAuthMount({
650
- database,
651
- emailAndPassword: { enabled: true },
652
- session: { cookieCache: { enabled: false } },
653
- });
654
- });
655
- ```
656
-
657
- `authDatabase(url, { max, application_name })` accepts an optional maximum connection count and PostgreSQL application name, passed to `pg.Pool`. Omit the settings to use pg’s defaults.
658
-
659
- Run this Effect in the host's scope. The pool logs idle-client errors at Debug and replaces failed connections on the next query; closing the scope disconnects its clients. A rejected auth handler returns HTTP 503 with `Authentication is temporarily unavailable`.
660
-
661
- The mount reads `BETTER_AUTH_SECRET` unless options supply `secret`. `PUBLIC_URL` supplies the default base URL, trusted origin and HTTPS secure-cookie setting; without it, the defaults accept loopback HTTP. Application options can override those defaults. RPC Origin policy remains an application choice.
662
-
663
- `AUTH_RATE_LIMIT_ENABLED` is a Config boolean that defaults to true and takes precedence over `options.rateLimit.enabled`. Each mount owns scoped in-memory buckets when `storage` is unset or `"memory"`. Application `customStorage`, `"database"` and `"secondary-storage"` selections pass through; Better Auth chooses the rules and client-IP keys.
664
-
665
- `TRUSTED_PROXY` supplies the same address and CIDR policy used by the host. An untrusted transport peer loses `x-forwarded-for` and the configured client-IP header before Better Auth sees the request. `AUTH_CLIENT_IP_HEADER` defaults to `x-forwarded-for`. With no trusted proxy, Better Auth ignores forwarded IPs and shares a rate-limit bucket per path.
666
-
667
- For email sign-in through `appHost`, the session record's `ipAddress` follows the same rule. With a trusted peer, `AUTH_CLIENT_IP_HEADER=x-real-ip` stores `X-Real-IP` even if `X-Forwarded-For` supplies a different address; the default header selects the rightmost untrusted address in the `X-Forwarded-For` chain, ignoring trusted proxy hops on the right. With an untrusted peer, neither header can supply the stored address. Sign-in attempts from an untrusted peer share one bucket per path; with a trusted peer and `x-real-ip`, changing `X-Forwarded-For` does not change the bucket, while changing `X-Real-IP` does.
668
-
669
- ### Bundled native clients
670
-
671
- For a Capacitor or similar WebView whose page is served from the app bundle, opt in with the auth host mount's `bearerSessions` option. It installs Better Auth's own `bearer({ requireSignature: true })` plugin from the existing dependency; do not add a second bearer plugin. The option is absent by default. List only bundled-client origins here, and include them in Better Auth's `trustedOrigins` as well.
672
-
673
- ```ts
674
- const nativeOrigins = ["capacitor://localhost", "https://localhost"];
675
- const mounted = yield* betterAuthMount(
676
- {
677
- database,
678
- trustedOrigins: [publicOrigin, ...nativeOrigins],
679
- session: { cookieCache: { enabled: false } },
680
- emailAndPassword: { enabled: true },
681
- },
682
- { bearerSessions: { origins: nativeOrigins } },
683
- );
684
- const sessions = {
685
- origin: trustedOrigins({ allow: [publicOrigin, ...nativeOrigins], missing: "allow" }),
686
- provider: betterAuthSessions(mounted.admittedSessions((headers) => mounted.auth.api.getSession({ headers }))),
687
- };
688
- const host = appHost({ group, handlers, routes: mounted.routes, sessions, nativeOrigins });
689
- ```
690
-
691
- Always wrap the session lookup in `admittedSessions`, even without a sign-in policy: it applies the mount's credential selection to the same request-local identity, profile and role middleware used by cookies. A same-origin request or a request without an Origin carrying the session cookie uses only that cookie, even if invalid or revoked; its bearer header cannot switch accounts or rescue it. Otherwise the signed bearer is resolved by Better Auth. Missing, unsigned, tampered, expired and revoked bearer sessions produce `Unauthorized` at protected RPCs.
692
-
693
- A native client signs in through `/api/auth/sign-in/email` with `credentials: "omit"` and its bundled Origin, reads the signed credential from the `set-auth-token` response header, and sends that exact value as `Authorization: Bearer <credential>` with `credentials: "omit"` on later auth and RPC requests. Persist it only in OS-backed secure storage, such as iOS Keychain or Android Keystore-backed storage; never use localStorage, sessionStorage or IndexedDB. Browser responses keep HttpOnly cookies and omit the plugin's token header and JSON token fields. Clients without a bundled Origin receive cookie responses.
694
-
695
- Native sign-out revokes the stored session. Signing in again while sending the current bearer replaces it and revokes the old session after successful sign-in. Streams keep their original request headers, so the old session ends with `Unauthorized` on the next revalidation; it never adopts the replacement. Keep cookie caching disabled for database-backed revocation and choose `streamRevalidationInterval` for the required delivery window.
696
-
697
- `appHost`'s `nativeOrigins` option admits those exact origins through the RPC transport guard and the auth routes. Wildcards, patterns and URLs with paths are rejected at startup. Keep the list aligned with `bearerSessions.origins`, Better Auth's `trustedOrigins` and the RPC session origin policy: the later origin policies alone cannot open the transport guard. Omit the option to keep the existing same-origin transport policy.
698
-
699
- The host answers native preflights with POST for RPC, GET and POST for auth, and only `Authorization` and `Content-Type` headers. Native responses echo the allowed origin exactly with `Vary: Origin`; auth responses expose `set-auth-token`. The host never enables CORS credentials. It strips cookies from admitted native requests before auth or RPC session resolution, so only the signed bearer session can authenticate them. This prevents native access from opening a cookie CSRF path, even if a caller sends a cookie. Resource authorization remains app-owned.
700
-
701
- Use the WebView's own fetch with `credentials: "omit"` for incremental NDJSON change streams and abort its request to release server work. A buffering native HTTP bridge cannot deliver that streaming behavior. The host still validates trusted proxy peers and forwarded authority, enforces NDJSON and body limits, uses only transport credentials, redacts diagnostics and authorizes sessions. Native HTTP callers without an Origin can exercise bearer RPC with an origin policy that explicitly permits missing Origins.
702
-
703
- ### Decide who may sign in
704
-
705
- Give the mount a sign-in policy as its second argument, and resolve RPC sessions through `admittedSessions` so a removal ends access on the next request:
706
-
707
- ```ts
708
- import { Config, Effect } from "effect";
709
- import { allowedAccounts } from "@shivaedev/platform/server/better-auth/allowedAccounts.ts";
710
- import { authDatabase, betterAuthMount } from "@shivaedev/platform/server/better-auth/mount.ts";
711
- import { betterAuthSessions } from "@shivaedev/platform/server/rpc-server/adapters/betterAuthSessions.ts";
712
- import { trustedOrigins } from "@shivaedev/platform/server/rpc-server/origin.ts";
713
-
714
- const authentication = Effect.gen(function* () {
715
- const database = yield* authDatabase(yield* Config.Redacted("DATABASE_URL"));
716
- const mounted = yield* betterAuthMount(
717
- { database, session: { cookieCache: { enabled: false } }, socialProviders: { github } },
718
- { signIn: { accounts: allowedAccounts, recheckInterval: "5 minutes", rule: inOrganization } },
719
- );
720
- yield* mounted.revokeUnadmitted;
721
- const sessions = {
722
- origin: trustedOrigins({ allow: ["https://app.example"], missing: "reject" }),
723
- provider: betterAuthSessions(mounted.admittedSessions((headers) => mounted.auth.api.getSession({ headers }))),
724
- };
725
- return { ...mounted, sessions };
726
- });
727
- ```
728
-
729
- `github` is the application's GitHub client settings. `inOrganization` is the application's rule, `(account: ProviderAccountValue) => Effect<boolean, E, R>`, which asks the provider whether that account belongs to its organization; the mount requires the rule's `R`, and its failures stay typed. Both parts are optional, and a user is admitted when one of their provider accounts is on the list and the rule admits that account.
730
-
731
- `allowedAccounts` reads `AUTH_ALLOWED_ACCOUNTS` through Effect Config and decodes it with the `AllowedAccounts` Schema: comma-separated `providerId:accountId` entries, such as `github:1001,github:1002` for two GitHub user IDs. A malformed or empty list stops the mount with a `ConfigError`. For another variable name, pass `Config.schema(AllowedAccounts, "NAME")` as `accounts`.
732
-
733
- At sign-in the mount installs the policy into Better Auth's own hooks. `user.validateUserInfo` checks the provider account from the provider's verified profile before Better Auth creates a user, so a refused sign-up leaves no user behind. Sign-ups without a provider account, such as email and password, are refused while a policy is set. `databaseHooks.session.create.before` checks the stored accounts of a returning user before Better Auth creates the session. A refused OAuth sign-in redirects to the error URL with `error=sign_in_refused`, and a refused API call answers HTTP 403 with code `sign_in_refused`. When the rule fails, the sign-in is refused with `sign_in_unavailable` and no user is created. The application's own `databaseHooks.session.create.before` runs before the policy's, and a session it refuses stays refused.
734
-
735
- A removal takes effect on the user's next request through `admittedSessions`: the list is read from Config at every check, the user is refused with `Unauthorized`, and Better Auth's internal adapter deletes every stored session of that user. With environment variables, the list changes when the application restarts with the new value; a Config provider whose values change at runtime applies a removal without a restart. The rule's answer for each provider account is reused for `recheckInterval`, five minutes by default, so a rule that turns false refuses the user on their first request after that interval. A failing rule, or a list that no longer decodes, answers `AuthUnavailable` and keeps the session.
736
-
737
- `revokeUnadmitted` checks every stored user against the current policy, deletes the sessions of each user it no longer admits and succeeds with `{ users, sessions }`, the number of users and sessions it revoked. Run it at startup, as above, or from an administrative command. It fails with the rule's error or with a `ConfigError`.
738
-
739
- Without `signIn`, the mount installs no sign-in policy hooks and `revokeUnadmitted` revokes nothing. Without either mount option, `admittedSessions` returns the lookup unchanged.
740
-
741
- ### Signed-in story preconditions
742
-
743
- Use `testUtils()` from `better-auth/plugins` in a test-only Better Auth instance with the host's database, secret and cookie policy. Keep the plugin out of production auth options.
744
-
745
- Use `authTestDatabase(pool)` from `@shivaedev/platform/server/better-auth/testDatabase.ts` when a story needs observations or faults in the default Better Auth PostgreSQL schema. It returns Effect readouts `users` (IDs and emails) and `sessions` (IDs, user IDs and emails), plus the test-only faults `expireSessions` and `omitImageColumn`. It never returns tokens, password hashes or provider credentials. These fixtures assume the default table and column mappings and operate on the supplied pool; use only an isolated test database. Application stories keep their auth SQL in this provider-owned boundary.
746
-
747
- ```ts
748
- import { betterAuth } from "better-auth";
749
- import { testUtils } from "better-auth/plugins";
750
- import { signedInUser } from "@shivaedev/platform/server/better-auth/testing.ts";
751
-
752
- const testAuth = betterAuth({
753
- ...options,
754
- plugins: [...(options.plugins ?? []), testUtils()],
755
- });
756
- const { user, headers, cookies } = await signedInUser(testAuth, {
757
- email: "member@example.test",
758
- name: "Member",
759
- providerAccounts: [{ providerId: "github", accountId: "123" }],
760
- role: "user,admin",
761
- });
762
- ```
763
-
764
- `options` is the application's auth configuration. `signedInUser` saves the supplied user fields, creates each optional `providerAccounts` entry for that user through Better Auth's internal adapter, and mints one session through Better Auth's `testUtils`, without OAuth or password hashing. The accounts carry no tokens or password. Omitting `providerAccounts` creates only the user and session. It returns Better Auth's login result: the user, session, signed request headers, browser cookies and token. Roles require the application's role plugin, such as Better Auth's `admin()`. Send `headers` to the real host, or pass `cookies` to test-story's `seedCookies` in a DOM story after setting its host location with `domFetch`. Keep a real sign-in story for each sign-in flow; feature stories start from the minted precondition.
765
-
766
- Use `storedProviderAccounts(auth, userId)` to observe credential storage through Better Auth's internal adapter. It returns account and provider IDs with `hasAccessToken`, `hasRefreshToken`, `hasIdToken` and `hasPassword` booleans. It never returns token values, passwords or password hashes. A DOM story kit that exposes its test auth instance and a session readout can use both helpers:
767
-
768
- ```ts
769
- import { Effect } from "effect";
770
- import { expect } from "vitest";
771
- import { seedCookies } from "@shivaedev/test-story/server/seedCookies.ts";
772
- import { signedInUser, storedProviderAccounts } from "@shivaedev/platform/server/better-auth/testing.ts";
773
-
774
- const member = app.trait("account", "a member starts signed in with GitHub", function* ({ auth }) {
775
- const { cookies } = yield* Effect.promise(() => signedInUser(auth, {
776
- email: "member@example.test",
777
- name: "Member",
778
- providerAccounts: [{ providerId: "github", accountId: "123" }],
779
- }));
780
- yield* seedCookies(cookies);
781
- });
782
-
783
- app.it("the member's provider account stores no credentials", [member], function* ({ session, story }) {
784
- const { user } = yield* session();
785
- const accounts = yield* Effect.promise(() => storedProviderAccounts(story.engine.auth, user.id));
786
- expect(accounts).toEqual([{
787
- providerId: "github",
788
- accountId: "123",
789
- hasAccessToken: false,
790
- hasRefreshToken: false,
791
- hasIdToken: false,
792
- hasPassword: false,
793
- }]);
794
- });
795
- ```
796
-
797
- With database-backed sessions and cookie caching disabled, revocation rejects that same minted session on the next protected HTTP or RPC request. Cookie caching and secondary storage can change revocation timing.
798
-
799
- ### Optional Better Auth storage on Effect Prisma
800
-
801
- When Better Auth's rows belong to an Effect Prisma database, give its adapter the same database service and runtime:
802
-
803
- ```ts
804
- import { betterAuth } from "better-auth";
805
- import { effectPrismaAdapter } from "@shivaedev/platform/server/better-auth/adapter.ts";
806
- import { makePlatformRuntime } from "@shivaedev/platform/server/runtime/makePlatform.ts";
807
- import { Database, DatabaseLive } from "./database.ts";
808
-
809
- export const runtime = makePlatformRuntime(DatabaseLive);
810
- export const auth = betterAuth({
811
- database: effectPrismaAdapter(Database, runtime, {
812
- modelName: (model) =>
813
- `Auth${model.length === 0 ? model : `${model[0]?.toUpperCase()}${model.slice(1)}`}`,
814
- }),
815
- });
816
- ```
817
-
818
- The application's database module owns its generated contract and Layer. This mapping selects `AuthUser` for Better Auth's `user` model. The adapter translates create, read, update, count and delete operations through Effect Prisma. It carries a Better Auth transaction's services through its Promise callback; a failed callback rolls the transaction back.
819
-
820
- An empty `update` filter returns null. Empty filters on `updateMany` and `deleteMany` affect all rows, so callers must choose those operations deliberately.
821
-
822
- ### In tests: one Prisma/tRPC composition
823
-
824
- Set up the application harness once in `test-support/`:
825
-
826
- ```ts
827
- import { Effect } from "effect";
828
- import { makePlatformIt } from "@shivaedev/platform/server/testing/makePlatformIt.ts";
829
- import { adapter, Database, router, TestLive } from "./application.ts";
830
-
831
- export const it = makePlatformIt(Database)({
832
- adapter,
833
- createCaller: (options = { actor: "default" }) => router.createCaller(options),
834
- extend: ({ db }) =>
835
- Effect.succeed({
836
- userExists: (id: string) => db.AuthUser.where({ id }).exists(),
837
- }),
838
- layer: TestLive,
839
- });
840
- ```
841
-
842
- `application.ts` supplies the application's Effect tRPC adapter, generated database service, router and test Layer. The example router has `createUser` and `findUser` procedures, and its caller context has an `actor` string. `extend` adds application helpers alongside `db`, `trpc` and `promise`; types are inferred from the database, caller and extension.
843
-
844
- Write each feature test against the caller and database:
845
-
846
- ```ts
847
- import { expect } from "@effect/vitest";
848
- import { Option } from "effect";
849
- import { it } from "./test-support/it.ts";
850
-
851
- it.effectApp("stores the user's email", function* ({ db, trpc, userExists }) {
852
- const id = crypto.randomUUID();
853
- const input = { email: `${id}@example.test`, id, name: "Ada" };
854
- const created = yield* trpc.createUser(input);
855
- const stored = Option.getOrThrow(yield* db.AuthUser.where({ id }).first());
856
-
857
- expect(stored.email).toBe(input.email);
858
- expect(yield* userExists(created.id)).toBe(true);
859
- });
860
- ```
861
-
862
- The direct database, tRPC caller and extension share the test's PostgreSQL transaction. Successful and expected-failing tests roll their writes back. `trpc({ actor: "admin" })` selects another caller context within the test. `promise(() => auth.api.getSession({ headers }))` runs a Promise boundary with the test's services, so Better Auth adapter calls inside it join the rollback transaction.
863
-
864
- ### API
865
-
866
- Import the module that defines the name; there is no package-root entry. Paths below follow `@shivaedev/platform/`.
867
-
868
- | Module | Names and purpose |
869
- | --- | --- |
870
- | `rpc/identity.ts` | `RequestId`, `Identity`, `OptionalIdentity`, `SessionUser`, `SessionUserWithProviderAccounts`: request-local services. |
871
- | `rpc/middleware.ts` | `RequestTracing`, `Authenticated`, `AuthenticatedUser`, `AuthenticatedUserWithProviderAccounts`, `MaybeAuthenticated`: native RPC middleware declarations. |
872
- | `rpc/permission.ts` | Native permission middleware declarations and predicates over resolved grants. |
873
- | `server/rpc-server/permissions.ts` | Permission middleware Layers and HTTP route guards. |
874
- | `server/appHost.ts` | `appHost`, `appDatabase`, `AppChanges`: scoped HTTP and PostgreSQL composition with loopback defaults and optional proxy trust. |
875
- | `server/boundedBody.ts` | `readBoundedBody`, `RequestBodyTooLarge`: bounded body bytes and a typed HTTP 413 failure. |
876
- | `server/otlpTracing.ts` | `otlpTracing`: opt-in Effect OTLP trace export for worker Layers. |
877
- | `server/rpc-server/session.ts` | `authenticatedLayer`, `maybeAuthenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, `withSessionUser`, `resolveSession`: session middleware implementations and the identity boundary. |
878
- | `server/rpc-server/adapters/betterAuthSessions.ts` | `betterAuthSessions(getSession, getProviderAccounts?)`: a session provider from Better Auth lookups. |
879
- | `server/rpc-server/origin.ts` | `trustedOrigins({ allow, missing })`: an exact Origin allowlist. |
880
- | `server/rpc-server/local.ts` | `localRpcGuard`, `loopbackOnly`, `sameOrigin`, `trustedProxyPeer`, `trustedProxyRanges`: loopback and proxy guards. |
881
- | `server/rpc-server/transportHeaders.ts` | `transportHeaders(rpcHeaders)`: the headers used for a transport-level decision. |
882
- | `server/rpc-server/boundary.ts` | `rpcBoundary(schema, { unexpected, message? })`: declared failures pass through, unexpected failures become one declared rejection. |
883
- | `server/rpc-server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`. |
884
- | `server/rpc-server/redact.ts`, `server/rpc-server/redactCause.ts`, `server/rpc-server/sensitive.ts` | `redact`, `redactCause`, `redactDiagnosticCause`, `redactDefect`, `redactingErrorReporter`, `isSensitiveKey`, `redactText`: diagnostic redaction. |
885
- | `server/schemaSensitiveKeys.ts`, `server/RedactionPolicy.ts` | `schemaSensitiveKeys(group, extraKeys?)`, `RedactionPolicy`: derive and provide an app's diagnostic key predicate. |
886
- | `server/redactingDiagnostics.ts`, `server/redactingTracer.ts`, `server/redactingRpcSerialization.ts` | `redactingDiagnostics(sensitive)`, `redactRecord(values, sensitive)`, `redactingTracer(sensitive)`, `redactingRpcSerialization(wire, sensitive)`: compose native diagnostic and NDJSON boundaries. |
887
- | `server/runtime/makePlatform.ts` | `makePlatformRuntime(layer, { developmentCacheKey? })`. |
888
- | `server/node-http/subscriptionSignal.ts` | `nodeSubscriptionSignal({ nodeRequest?, request?, signals? })`, returning `{ signal, dispose }`. |
889
- | `server/better-auth/mount.ts` | `betterAuthMount(options, { signIn?, bearerSessions? })`, returning `{ auth, routes, admittedSessions, revokeUnadmitted }`, and `authDatabase(url, { max?, application_name? }?)`: native auth routes, the sign-in policy and a scoped PostgreSQL pool. |
890
- | `server/better-auth/allowedAccounts.ts` | `AllowedAccounts`, `allowedAccounts`: the provider-account list Schema and its `AUTH_ALLOWED_ACCOUNTS` Config. |
891
- | `server/better-auth/signInGate.ts` | `SignInPolicy`: the `accounts`, `rule` and `recheckInterval` of a sign-in policy. |
892
- | `server/better-auth/revokeUnadmitted.ts` | `RevokedSessions`: the `{ users, sessions }` counts of a revocation. |
893
- | `server/better-auth/testDatabase.ts` | `authTestDatabase(pool)`: test-only identity/session readouts and faults for the default PostgreSQL auth schema. |
894
- | `server/better-auth/testing.ts` | `signedInUser(auth, fields)`, `storedProviderAccounts(auth, userId)`: test-only minted user sessions and credential storage observations. |
895
- | `server/better-auth/adapter.ts` | `effectPrismaAdapter(Database, runtime, options?)`: a Better Auth adapter over Effect Prisma; `modelName` maps model names. |
896
- | `server/testing/makePlatformIt.ts` | `makePlatformIt(Database)({ adapter, createCaller, layer, extend? })`. |
897
-
898
- ### Manage app users
899
-
900
- `server/better-auth/users.ts` provides `listUsers({ limit, cursor? })` and `changeUserRole({ userId, role, grant })` using the existing Effect SQL client and Better Auth's default PostgreSQL user table with its admin plugin. Browser-safe schemas, Platform roles (`user`, `admin`, `owner`) and the typed `LastOwner` failure live in `rpc/userRoles.ts`. The admin package supplies the protected contract and React view.
901
-
902
- Role writes require an owner `SessionUser`, serialize role changes in a transaction, and reject removal of the final owner. They preserve unrelated roles and publish the `admin.users` invalidation after commit. Successful changes emit structured Effect logs with actor, target, role, action and UTC timestamp. Platform has no durable audit-history store. The host must use the same database as authentication; custom Better Auth table names and columns need their own integration.
903
-
904
- ### Install, setup and limits
905
-
906
- ```sh
907
- pnpm add @shivaedev/platform effect@4.0.5
908
- ```
909
-
910
- Effect is the only required peer. The peer-free implementation lives in the shared `rpc/` folder and the `server/node-http/`, `server/rpc-server/` and `server/runtime/` folders; a module's import path is its path under `src/`. The core RPC declarations, server middleware, runtime and Node HTTP modules can be imported without the optional peers, including the Promise-based `betterAuthSessions` function. The runtime uses Node's `AsyncLocalStorage`; browser consumers import the shared `rpc/` modules and the error schemas from `@shivaedev/effect-contract/errors/taxonomy.ts`.
911
-
912
- Install the optional peers for the selected integration:
913
-
914
- | Integration | Additional peers |
39
+ | Job | Package |
915
40
  | --- | --- |
916
- | `server/boundedBody.ts` | `@effect/platform-node` |
917
- | `server/appHost.ts` | `@effect/platform-node`, `@effect/sql-pg` |
918
- | `server/better-auth/mount.ts` | `better-auth`, `pg` |
919
- | `server/better-auth/adapter.ts` | `better-auth`, `@shivaedev/effect-prisma`, `@prisma-next/sql-orm-client` |
920
- | `server/testing/makePlatformIt.ts` | `@effect/vitest`, `@shivaedev/effect-prisma`, `@shivaedev/effect-trpc`, `@trpc/server` |
921
-
922
- - The package needs Node 24 or newer.
923
- - Keep the auth provider's configuration, cookie settings and resource authorization in the application. The session adapter takes a session lookup and an optional provider-account lookup and returns a session result; it does not write provider refresh cookies into RPC responses.
924
- - Without an `HttpServerRequest`, `transportHeaders` falls back to the supplied RPC headers. An application using another transport must decide what headers it can trust.
925
- - `appHost` adds tracing last on its server-side copy of the group. When composing a native RPC server directly, add `RequestTracing` last on the group so it wraps authentication too; see the [native-server example](https://github.com/ShivaeDev/platform/blob/main/docs/framework/request-context.md#request-id-identity-and-logging). Middleware outside that tracing boundary is responsible for its own diagnostics.
926
- - Redaction recognizes declared field names and common credential shapes. Mark sensitive fields in RPC schemas and configure extra names once with `config.sensitiveKeys`. Keep sensitive values out of ordinary prose.
927
- - A development cache key is ignored when `NODE_ENV` is `production`. The application owns runtime disposal.
928
- - The Better Auth storage adapter's default model mapping capitalizes the model name. Supply `modelName` for a generated schema with another naming convention. Native Better Auth joins (`advanced.database.joins`) are rejected; leave that option off so Better Auth reads related rows with separate queries.
929
-
930
- The [framework request-context guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/request-context.md) explains the browser and native-client Origin choices.
41
+ | Services and Layers | [`@shivaedev/service`](https://github.com/ShivaeDev/platform/tree/main/packages/service#readme) |
42
+ | Persistence, repositories and migrations | [`@shivaedev/sql`](https://github.com/ShivaeDev/platform/tree/main/packages/sql#readme) |
43
+ | After-commit changes | [`@shivaedev/changes`](https://github.com/ShivaeDev/platform/tree/main/packages/changes#readme) |
44
+ | Queries, commands and live contracts | [`@shivaedev/contract`](https://github.com/ShivaeDev/platform/tree/main/packages/contract#readme) |
45
+ | Shared expected failures and redaction | [`@shivaedev/errors`](https://github.com/ShivaeDev/platform/tree/main/packages/errors#readme) |
46
+ | Request identity, sessions, permissions and Better Auth | [`@shivaedev/identity`](https://github.com/ShivaeDev/platform/tree/main/packages/identity#readme) |
47
+ | Roles and permission sets | [`@shivaedev/access`](https://github.com/ShivaeDev/platform/tree/main/packages/access#readme) |
48
+ | The application host | [`@shivaedev/server`](https://github.com/ShivaeDev/platform/tree/main/packages/server#readme) |
49
+ | Calls to outside HTTP APIs | [`@shivaedev/http`](https://github.com/ShivaeDev/platform/tree/main/packages/http#readme) |
50
+ | Client state in React | [`@shivaedev/react`](https://github.com/ShivaeDev/platform/tree/main/packages/react#readme) |
51
+ | Forms | [`@shivaedev/form`](https://github.com/ShivaeDev/platform/tree/main/packages/form#readme) |
52
+ | Background jobs | [`@shivaedev/jobs`](https://github.com/ShivaeDev/platform/tree/main/packages/jobs#readme) |
53
+ | Admin pages | [`@shivaedev/admin`](https://github.com/ShivaeDev/platform/tree/main/packages/admin#readme) |
54
+ | GitHub integration | [`@shivaedev/github`](https://github.com/ShivaeDev/platform/tree/main/packages/github#readme) |
55
+ | Local PostgreSQL for development | [`@shivaedev/local-postgres`](https://github.com/ShivaeDev/platform/tree/main/packages/local-postgres#readme) |
56
+ | Shared TypeScript types | [`@shivaedev/types`](https://github.com/ShivaeDev/platform/tree/main/packages/types#readme) |
57
+
58
+ Tests use [`@shivaedev/test-story`](https://github.com/ShivaeDev/platform/tree/main/packages/test-story#readme) and checks use [`@shivaedev/quality`](https://github.com/ShivaeDev/platform/tree/main/packages/quality#readme), both as development dependencies.