@porulle/core 0.11.0 → 0.13.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 (289) hide show
  1. package/dist/auth/auth-schema-guard.d.ts +2444 -0
  2. package/dist/auth/auth-schema-guard.d.ts.map +1 -0
  3. package/dist/auth/auth-schema-guard.js +113 -0
  4. package/dist/auth/auth-schema.d.ts +228 -0
  5. package/dist/auth/auth-schema.d.ts.map +1 -1
  6. package/dist/auth/auth-schema.js +24 -2
  7. package/dist/auth/middleware.d.ts +1 -0
  8. package/dist/auth/middleware.d.ts.map +1 -1
  9. package/dist/auth/middleware.js +13 -5
  10. package/dist/auth/org.d.ts +8 -2
  11. package/dist/auth/org.d.ts.map +1 -1
  12. package/dist/auth/org.js +12 -4
  13. package/dist/auth/organization-guard.d.ts +5 -0
  14. package/dist/auth/organization-guard.d.ts.map +1 -0
  15. package/dist/auth/organization-guard.js +124 -0
  16. package/dist/auth/permissions.d.ts +10 -0
  17. package/dist/auth/permissions.d.ts.map +1 -1
  18. package/dist/auth/permissions.js +31 -7
  19. package/dist/auth/role-authority.d.ts +44 -0
  20. package/dist/auth/role-authority.d.ts.map +1 -0
  21. package/dist/auth/role-authority.js +85 -0
  22. package/dist/auth/setup.d.ts.map +1 -1
  23. package/dist/auth/setup.js +17 -0
  24. package/dist/auth/strict-org-resolution.d.ts.map +1 -1
  25. package/dist/auth/strict-org-resolution.js +9 -1
  26. package/dist/auth/types.d.ts +1 -1
  27. package/dist/auth/types.d.ts.map +1 -1
  28. package/dist/config/defaults.d.ts.map +1 -1
  29. package/dist/config/defaults.js +2 -0
  30. package/dist/config/types.d.ts +30 -4
  31. package/dist/config/types.d.ts.map +1 -1
  32. package/dist/hooks/checkout.d.ts.map +1 -1
  33. package/dist/hooks/checkout.js +10 -9
  34. package/dist/index.d.ts +6 -5
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +4 -3
  37. package/dist/interfaces/rest/audit-middleware.d.ts.map +1 -1
  38. package/dist/interfaces/rest/audit-middleware.js +2 -0
  39. package/dist/interfaces/rest/customer-portal.d.ts.map +1 -1
  40. package/dist/interfaces/rest/customer-portal.js +9 -8
  41. package/dist/interfaces/rest/route-coverage.d.ts +14 -0
  42. package/dist/interfaces/rest/route-coverage.d.ts.map +1 -0
  43. package/dist/interfaces/rest/route-coverage.js +81 -0
  44. package/dist/interfaces/rest/router.d.ts +7 -2
  45. package/dist/interfaces/rest/router.d.ts.map +1 -1
  46. package/dist/interfaces/rest/router.js +8 -4
  47. package/dist/interfaces/rest/routes/admin/compensation-failures.d.ts.map +1 -1
  48. package/dist/interfaces/rest/routes/admin/compensation-failures.js +7 -5
  49. package/dist/interfaces/rest/routes/admin/custom-field-proposals.js +2 -2
  50. package/dist/interfaces/rest/routes/admin/permissions.d.ts +1 -1
  51. package/dist/interfaces/rest/routes/admin/permissions.d.ts.map +1 -1
  52. package/dist/interfaces/rest/routes/admin/permissions.js +2 -0
  53. package/dist/interfaces/rest/routes/admin/staff.d.ts.map +1 -1
  54. package/dist/interfaces/rest/routes/admin/staff.js +126 -66
  55. package/dist/interfaces/rest/routes/admin-jobs.js +3 -3
  56. package/dist/interfaces/rest/routes/audit.js +3 -3
  57. package/dist/interfaces/rest/routes/carts.d.ts.map +1 -1
  58. package/dist/interfaces/rest/routes/carts.js +13 -10
  59. package/dist/interfaces/rest/routes/catalog.d.ts.map +1 -1
  60. package/dist/interfaces/rest/routes/catalog.js +10 -2
  61. package/dist/interfaces/rest/routes/checkout.d.ts.map +1 -1
  62. package/dist/interfaces/rest/routes/checkout.js +30 -35
  63. package/dist/interfaces/rest/routes/documents.d.ts.map +1 -1
  64. package/dist/interfaces/rest/routes/documents.js +10 -5
  65. package/dist/interfaces/rest/routes/inventory.d.ts.map +1 -1
  66. package/dist/interfaces/rest/routes/inventory.js +2 -0
  67. package/dist/interfaces/rest/routes/media.d.ts.map +1 -1
  68. package/dist/interfaces/rest/routes/media.js +7 -3
  69. package/dist/interfaces/rest/routes/orders.d.ts.map +1 -1
  70. package/dist/interfaces/rest/routes/orders.js +26 -8
  71. package/dist/interfaces/rest/routes/pricing.js +2 -2
  72. package/dist/interfaces/rest/routes/promotions.d.ts.map +1 -1
  73. package/dist/interfaces/rest/routes/promotions.js +13 -10
  74. package/dist/interfaces/rest/routes/search.d.ts.map +1 -1
  75. package/dist/interfaces/rest/routes/search.js +2 -1
  76. package/dist/interfaces/rest/schemas/carts.d.ts +7 -0
  77. package/dist/interfaces/rest/schemas/carts.d.ts.map +1 -1
  78. package/dist/interfaces/rest/schemas/customer-portal.d.ts +35 -0
  79. package/dist/interfaces/rest/schemas/customer-portal.d.ts.map +1 -1
  80. package/dist/interfaces/rest/schemas/orders.d.ts +204 -0
  81. package/dist/interfaces/rest/schemas/orders.d.ts.map +1 -1
  82. package/dist/interfaces/rest/schemas/responses.d.ts +71 -0
  83. package/dist/interfaces/rest/schemas/responses.d.ts.map +1 -1
  84. package/dist/interfaces/rest/utils.d.ts +15 -0
  85. package/dist/interfaces/rest/utils.d.ts.map +1 -1
  86. package/dist/interfaces/rest/utils.js +45 -2
  87. package/dist/kernel/compensation/executor.js +2 -2
  88. package/dist/kernel/database/tx-context.d.ts +8 -0
  89. package/dist/kernel/database/tx-context.d.ts.map +1 -1
  90. package/dist/kernel/database/tx-context.js +13 -0
  91. package/dist/kernel/hooks/create-context.d.ts +2 -0
  92. package/dist/kernel/hooks/create-context.d.ts.map +1 -1
  93. package/dist/kernel/hooks/create-context.js +1 -0
  94. package/dist/kernel/hooks/types.d.ts +2 -0
  95. package/dist/kernel/hooks/types.d.ts.map +1 -1
  96. package/dist/kernel/plugin/manifest.d.ts.map +1 -1
  97. package/dist/kernel/plugin/manifest.js +9 -5
  98. package/dist/modules/analytics/service.js +2 -2
  99. package/dist/modules/audit/service.js +3 -3
  100. package/dist/modules/cart/repository/index.d.ts +13 -7
  101. package/dist/modules/cart/repository/index.d.ts.map +1 -1
  102. package/dist/modules/cart/repository/index.js +16 -10
  103. package/dist/modules/cart/schema.d.ts +17 -0
  104. package/dist/modules/cart/schema.d.ts.map +1 -1
  105. package/dist/modules/cart/schema.js +4 -0
  106. package/dist/modules/cart/service.d.ts +22 -9
  107. package/dist/modules/cart/service.d.ts.map +1 -1
  108. package/dist/modules/cart/service.js +57 -33
  109. package/dist/modules/catalog/brand-service.js +7 -7
  110. package/dist/modules/catalog/category-service.js +7 -7
  111. package/dist/modules/catalog/entity-service.d.ts +14 -7
  112. package/dist/modules/catalog/entity-service.d.ts.map +1 -1
  113. package/dist/modules/catalog/entity-service.js +109 -31
  114. package/dist/modules/catalog/read-policy.d.ts +9 -0
  115. package/dist/modules/catalog/read-policy.d.ts.map +1 -0
  116. package/dist/modules/catalog/read-policy.js +8 -0
  117. package/dist/modules/catalog/repository/index.d.ts +3 -2
  118. package/dist/modules/catalog/repository/index.d.ts.map +1 -1
  119. package/dist/modules/catalog/repository/index.js +14 -4
  120. package/dist/modules/catalog/service.d.ts +15 -13
  121. package/dist/modules/catalog/service.d.ts.map +1 -1
  122. package/dist/modules/catalog/service.js +25 -18
  123. package/dist/modules/customers/module.d.ts.map +1 -1
  124. package/dist/modules/customers/module.js +1 -0
  125. package/dist/modules/customers/service.d.ts +2 -0
  126. package/dist/modules/customers/service.d.ts.map +1 -1
  127. package/dist/modules/customers/service.js +21 -20
  128. package/dist/modules/documents/module.d.ts.map +1 -1
  129. package/dist/modules/documents/module.js +1 -0
  130. package/dist/modules/documents/service.d.ts +18 -4
  131. package/dist/modules/documents/service.d.ts.map +1 -1
  132. package/dist/modules/documents/service.js +54 -16
  133. package/dist/modules/fulfillment/module.d.ts.map +1 -1
  134. package/dist/modules/fulfillment/module.js +1 -0
  135. package/dist/modules/fulfillment/service.d.ts +2 -0
  136. package/dist/modules/fulfillment/service.d.ts.map +1 -1
  137. package/dist/modules/fulfillment/service.js +15 -6
  138. package/dist/modules/inventory/service.d.ts.map +1 -1
  139. package/dist/modules/inventory/service.js +15 -14
  140. package/dist/modules/media/service.js +6 -6
  141. package/dist/modules/orders/guest-access.d.ts +27 -0
  142. package/dist/modules/orders/guest-access.d.ts.map +1 -0
  143. package/dist/modules/orders/guest-access.js +46 -0
  144. package/dist/modules/orders/module.d.ts.map +1 -1
  145. package/dist/modules/orders/module.js +1 -0
  146. package/dist/modules/orders/quote.d.ts.map +1 -1
  147. package/dist/modules/orders/quote.js +1 -0
  148. package/dist/modules/orders/repository/index.d.ts +1 -1
  149. package/dist/modules/orders/repository/index.d.ts.map +1 -1
  150. package/dist/modules/orders/repository/index.js +2 -2
  151. package/dist/modules/orders/schema.d.ts +17 -0
  152. package/dist/modules/orders/schema.d.ts.map +1 -1
  153. package/dist/modules/orders/schema.js +5 -3
  154. package/dist/modules/orders/service.d.ts +16 -7
  155. package/dist/modules/orders/service.d.ts.map +1 -1
  156. package/dist/modules/orders/service.js +184 -55
  157. package/dist/modules/pricing/module.d.ts.map +1 -1
  158. package/dist/modules/pricing/module.js +1 -0
  159. package/dist/modules/pricing/service.d.ts +2 -0
  160. package/dist/modules/pricing/service.d.ts.map +1 -1
  161. package/dist/modules/pricing/service.js +12 -11
  162. package/dist/modules/promotions/module.d.ts.map +1 -1
  163. package/dist/modules/promotions/module.js +1 -0
  164. package/dist/modules/promotions/service.d.ts +3 -0
  165. package/dist/modules/promotions/service.d.ts.map +1 -1
  166. package/dist/modules/promotions/service.js +19 -11
  167. package/dist/modules/search/adapter.d.ts +6 -0
  168. package/dist/modules/search/adapter.d.ts.map +1 -1
  169. package/dist/modules/search/module.d.ts.map +1 -1
  170. package/dist/modules/search/module.js +1 -0
  171. package/dist/modules/search/service.d.ts +1 -0
  172. package/dist/modules/search/service.d.ts.map +1 -1
  173. package/dist/modules/search/service.js +57 -6
  174. package/dist/modules/settings/module.d.ts.map +1 -1
  175. package/dist/modules/settings/module.js +1 -0
  176. package/dist/modules/settings/service.d.ts +3 -0
  177. package/dist/modules/settings/service.d.ts.map +1 -1
  178. package/dist/modules/settings/service.js +6 -4
  179. package/dist/modules/shipping/service.js +9 -9
  180. package/dist/modules/tax/module.d.ts.map +1 -1
  181. package/dist/modules/tax/module.js +1 -0
  182. package/dist/modules/tax/service.d.ts +3 -0
  183. package/dist/modules/tax/service.d.ts.map +1 -1
  184. package/dist/modules/tax/service.js +11 -9
  185. package/dist/modules/webhooks/hook.js +2 -2
  186. package/dist/modules/webhooks/module.d.ts.map +1 -1
  187. package/dist/modules/webhooks/module.js +1 -0
  188. package/dist/modules/webhooks/service.d.ts +2 -0
  189. package/dist/modules/webhooks/service.d.ts.map +1 -1
  190. package/dist/modules/webhooks/service.js +4 -4
  191. package/dist/runtime/server.d.ts.map +1 -1
  192. package/dist/runtime/server.js +10 -2
  193. package/dist/test-utils/create-pglite-adapter.d.ts.map +1 -1
  194. package/dist/test-utils/create-pglite-adapter.js +35 -13
  195. package/dist/test-utils/create-test-config.d.ts.map +1 -1
  196. package/dist/test-utils/create-test-config.js +4 -0
  197. package/dist/test-utils/rest-api-test-utils.d.ts.map +1 -1
  198. package/dist/test-utils/rest-api-test-utils.js +2 -0
  199. package/dist/test-utils/test-actors.js +2 -2
  200. package/dist/utils/id.d.ts +2 -0
  201. package/dist/utils/id.d.ts.map +1 -1
  202. package/dist/utils/id.js +11 -0
  203. package/package.json +6 -5
  204. package/src/auth/auth-schema-guard.ts +143 -0
  205. package/src/auth/auth-schema.ts +50 -19
  206. package/src/auth/middleware.ts +17 -5
  207. package/src/auth/org.ts +15 -3
  208. package/src/auth/organization-guard.ts +158 -0
  209. package/src/auth/permissions.ts +31 -8
  210. package/src/auth/role-authority.ts +107 -0
  211. package/src/auth/setup.ts +17 -0
  212. package/src/auth/strict-org-resolution.ts +7 -1
  213. package/src/auth/types.ts +1 -1
  214. package/src/config/defaults.ts +2 -0
  215. package/src/config/types.ts +29 -4
  216. package/src/hooks/checkout.ts +19 -12
  217. package/src/index.ts +16 -6
  218. package/src/interfaces/rest/audit-middleware.ts +2 -0
  219. package/src/interfaces/rest/customer-portal.ts +31 -24
  220. package/src/interfaces/rest/route-coverage.ts +103 -0
  221. package/src/interfaces/rest/router.ts +16 -10
  222. package/src/interfaces/rest/routes/admin/compensation-failures.ts +8 -5
  223. package/src/interfaces/rest/routes/admin/custom-field-proposals.ts +2 -2
  224. package/src/interfaces/rest/routes/admin/permissions.ts +3 -1
  225. package/src/interfaces/rest/routes/admin/staff.ts +161 -72
  226. package/src/interfaces/rest/routes/admin-jobs.ts +3 -3
  227. package/src/interfaces/rest/routes/audit.ts +3 -3
  228. package/src/interfaces/rest/routes/carts.ts +17 -7
  229. package/src/interfaces/rest/routes/catalog.ts +11 -0
  230. package/src/interfaces/rest/routes/checkout.ts +41 -38
  231. package/src/interfaces/rest/routes/documents.ts +15 -1
  232. package/src/interfaces/rest/routes/inventory.ts +2 -0
  233. package/src/interfaces/rest/routes/media.ts +8 -3
  234. package/src/interfaces/rest/routes/orders.ts +27 -8
  235. package/src/interfaces/rest/routes/pricing.ts +2 -2
  236. package/src/interfaces/rest/routes/promotions.ts +12 -9
  237. package/src/interfaces/rest/routes/search.ts +3 -1
  238. package/src/interfaces/rest/utils.ts +61 -2
  239. package/src/kernel/compensation/executor.ts +2 -2
  240. package/src/kernel/database/tx-context.ts +25 -0
  241. package/src/kernel/hooks/create-context.ts +3 -0
  242. package/src/kernel/hooks/types.ts +2 -0
  243. package/src/kernel/plugin/manifest.ts +9 -5
  244. package/src/modules/analytics/service.ts +2 -2
  245. package/src/modules/audit/service.ts +3 -3
  246. package/src/modules/cart/repository/index.ts +22 -8
  247. package/src/modules/cart/schema.ts +4 -0
  248. package/src/modules/cart/service.ts +62 -27
  249. package/src/modules/catalog/brand-service.ts +7 -7
  250. package/src/modules/catalog/category-service.ts +7 -7
  251. package/src/modules/catalog/entity-service.ts +117 -35
  252. package/src/modules/catalog/read-policy.ts +16 -0
  253. package/src/modules/catalog/repository/index.ts +19 -3
  254. package/src/modules/catalog/service.ts +46 -31
  255. package/src/modules/customers/module.ts +2 -0
  256. package/src/modules/customers/service.ts +23 -22
  257. package/src/modules/documents/module.ts +2 -0
  258. package/src/modules/documents/service.ts +74 -11
  259. package/src/modules/fulfillment/module.ts +2 -0
  260. package/src/modules/fulfillment/service.ts +17 -6
  261. package/src/modules/inventory/service.ts +15 -24
  262. package/src/modules/media/service.ts +6 -6
  263. package/src/modules/orders/guest-access.ts +55 -0
  264. package/src/modules/orders/module.ts +1 -0
  265. package/src/modules/orders/quote.ts +1 -0
  266. package/src/modules/orders/repository/index.ts +2 -0
  267. package/src/modules/orders/schema.ts +5 -3
  268. package/src/modules/orders/service.ts +302 -52
  269. package/src/modules/pricing/module.ts +2 -0
  270. package/src/modules/pricing/service.ts +14 -16
  271. package/src/modules/promotions/module.ts +2 -0
  272. package/src/modules/promotions/service.ts +25 -16
  273. package/src/modules/search/adapter.ts +6 -0
  274. package/src/modules/search/module.ts +1 -0
  275. package/src/modules/search/service.ts +55 -6
  276. package/src/modules/settings/module.ts +2 -0
  277. package/src/modules/settings/service.ts +8 -4
  278. package/src/modules/shipping/service.ts +9 -9
  279. package/src/modules/tax/module.ts +1 -0
  280. package/src/modules/tax/service.ts +13 -9
  281. package/src/modules/webhooks/hook.ts +2 -2
  282. package/src/modules/webhooks/module.ts +2 -0
  283. package/src/modules/webhooks/service.ts +6 -4
  284. package/src/runtime/server.ts +16 -2
  285. package/src/test-utils/create-pglite-adapter.ts +34 -12
  286. package/src/test-utils/create-test-config.ts +10 -6
  287. package/src/test-utils/rest-api-test-utils.ts +2 -0
  288. package/src/test-utils/test-actors.ts +2 -2
  289. package/src/utils/id.ts +20 -0
@@ -0,0 +1,158 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import { and, eq } from "drizzle-orm";
3
+ import type { CommerceConfig } from "../config/types.js";
4
+ import type { DrizzleDatabase } from "../kernel/database/drizzle-db.js";
5
+ import { invitation, member } from "./auth-schema.js";
6
+ import { canGrantRole, granterForRole, isCompositeRole } from "./role-authority.js";
7
+
8
+ /**
9
+ * Guards Better Auth's organization endpoints, which this repository mounts but
10
+ * does not govern.
11
+ *
12
+ * Red-team round 6 found two problems behind that mount.
13
+ *
14
+ * Invitation acceptance re-checked nothing: an invitation minted a member at
15
+ * the authority its inviter held up to seven days ago, so a demoted or revoked
16
+ * inviter's outstanding invitation still handed out ownership — a full
17
+ * organization takeover. Acceptance now re-reads the inviter's current
18
+ * authority before the grant is allowed through.
19
+ *
20
+ * And the plugin's own membership writers are a second role-changing surface
21
+ * running none of the rules `admin/staff.ts` enforces: no permission
22
+ * containment, no rank floor, no last-owner invariant, and they accept
23
+ * comma-composite role strings that `admin/staff.ts` refuses. They are refused
24
+ * here. `admin/staff.ts` is this repository's governed membership surface, and
25
+ * having one is worth more than making two of them agree.
26
+ */
27
+
28
+ const ORGANIZATION_PREFIX = "/api/auth/organization/";
29
+
30
+ /**
31
+ * Better Auth endpoints that write membership or define what a role may do.
32
+ *
33
+ * `invite-member` currently throws for every role instead of refusing: the
34
+ * plugin is configured with commerce permission arrays where its access-control
35
+ * model expects `Role` objects exposing `.authorize()`, so its permission check
36
+ * dies of type confusion. That is fail-closed by accident, and the accident is
37
+ * one "fix the roles wiring" commit away from being fail-open. Refusing here
38
+ * makes the closure deliberate, so repairing that wiring cannot quietly open an
39
+ * ungoverned door. `update-member-role` is not even inert today — Better Auth
40
+ * short-circuits it for organization creators, so an owner reaches it.
41
+ */
42
+ const REFUSED_ENDPOINTS = new Set([
43
+ "invite-member",
44
+ "update-member-role",
45
+ "remove-member",
46
+ "leave",
47
+ "create-role",
48
+ "update-role",
49
+ "delete-role",
50
+ ]);
51
+
52
+ function endpointName(path: string): string | null {
53
+ const normalized = path.replace(/\/+$/, "");
54
+ return normalized.startsWith(ORGANIZATION_PREFIX)
55
+ ? normalized.slice(ORGANIZATION_PREFIX.length)
56
+ : null;
57
+ }
58
+
59
+ async function readJsonBody(request: Request): Promise<Record<string, unknown>> {
60
+ try {
61
+ return (await request.clone().json()) as Record<string, unknown>;
62
+ } catch {
63
+ return {};
64
+ }
65
+ }
66
+
67
+ export function organizationGuard(
68
+ db: DrizzleDatabase,
69
+ config: CommerceConfig,
70
+ ): MiddlewareHandler {
71
+ return async (c, next) => {
72
+ if (c.req.method !== "POST") {
73
+ await next();
74
+ return;
75
+ }
76
+
77
+ const endpoint = endpointName(c.req.path);
78
+ if (endpoint === null) {
79
+ await next();
80
+ return;
81
+ }
82
+
83
+ if (REFUSED_ENDPOINTS.has(endpoint)) {
84
+ return c.json(
85
+ {
86
+ error: {
87
+ code: "FORBIDDEN",
88
+ message: `"${endpoint}" is not a governed membership surface. Use /api/admin/staff, which enforces permission containment, the rank floor, and the last-owner invariant.`,
89
+ },
90
+ },
91
+ 403,
92
+ );
93
+ }
94
+
95
+ if (endpoint !== "accept-invitation") {
96
+ await next();
97
+ return;
98
+ }
99
+
100
+ const body = await readJsonBody(c.req.raw);
101
+ const invitationId = typeof body.invitationId === "string" ? body.invitationId : null;
102
+ if (!invitationId) {
103
+ await next();
104
+ return;
105
+ }
106
+
107
+ const rows = await db
108
+ .select()
109
+ .from(invitation)
110
+ .where(eq(invitation.id, invitationId));
111
+ const pending = rows[0];
112
+ // Missing, already-answered, or expired invitations are Better Auth's own
113
+ // error surface — do not duplicate its messages here.
114
+ if (!pending || pending.status !== "pending") {
115
+ await next();
116
+ return;
117
+ }
118
+
119
+ const invitedRole = pending.role ?? "member";
120
+ const inviterRows = await db
121
+ .select({ role: member.role })
122
+ .from(member)
123
+ .where(
124
+ and(
125
+ eq(member.organizationId, pending.organizationId),
126
+ eq(member.userId, pending.inviterId),
127
+ ),
128
+ );
129
+ const inviterRole = inviterRows[0]?.role;
130
+
131
+ const stillAuthorized =
132
+ inviterRole !== undefined &&
133
+ !isCompositeRole(invitedRole) &&
134
+ canGrantRole(config, granterForRole(config, inviterRole), invitedRole);
135
+
136
+ if (stillAuthorized) {
137
+ await next();
138
+ return;
139
+ }
140
+
141
+ // The grant is dead: burn it rather than leaving it to be retried.
142
+ await db
143
+ .update(invitation)
144
+ .set({ status: "canceled" })
145
+ .where(and(eq(invitation.id, invitationId), eq(invitation.status, "pending")));
146
+
147
+ return c.json(
148
+ {
149
+ error: {
150
+ code: "FORBIDDEN",
151
+ message:
152
+ "This invitation is no longer valid: the member who sent it can no longer grant that role.",
153
+ },
154
+ },
155
+ 403,
156
+ );
157
+ };
158
+ }
@@ -1,16 +1,18 @@
1
1
  import { CommerceForbiddenError } from "../kernel/errors.js";
2
2
  import type { Actor } from "./types.js";
3
3
 
4
- export function assertPermission(actor: Actor | null, required: string): void {
5
- if (!actor) {
6
- throw new CommerceForbiddenError("Authentication required.");
7
- }
8
-
9
- if (actor.permissions.includes("*:*")) return;
4
+ export function hasPermission(actor: Actor | null, required: string): boolean {
5
+ if (!actor) return false;
6
+ if (actor.permissions.includes("*:*")) return true;
10
7
 
11
8
  const [resource] = required.split(":");
12
- if (resource && actor.permissions.includes(`${resource}:*`)) return;
13
- if (actor.permissions.includes(required)) return;
9
+ if (resource && actor.permissions.includes(`${resource}:*`)) return true;
10
+ return actor.permissions.includes(required);
11
+ }
12
+
13
+ export function assertPermission(actor: Actor | null, required: string): void {
14
+ if (hasPermission(actor, required)) return;
15
+ if (!actor) throw new CommerceForbiddenError("Authentication required.");
14
16
 
15
17
  throw new CommerceForbiddenError(
16
18
  `Permission "${required}" is required. Your role "${actor.role}" does not include this permission.`,
@@ -22,7 +24,28 @@ export function assertOwnership(actor: Actor | null, resourceOwnerId: string | n
22
24
  throw new CommerceForbiddenError("Authentication required.");
23
25
  }
24
26
  if (actor.permissions.includes("*:*")) return;
27
+ if (!actor.userId || !resourceOwnerId) {
28
+ throw new CommerceForbiddenError("You do not have access to this resource.");
29
+ }
25
30
  if (actor.userId !== resourceOwnerId) {
26
31
  throw new CommerceForbiddenError("You do not have access to this resource.");
27
32
  }
28
33
  }
34
+
35
+ /**
36
+ * The actor's user id, for code that keys a per-person resource on it.
37
+ *
38
+ * An actor without a user identity — a store resolver, an API key — has no
39
+ * owner key at all. Passing its absence through as one would make every such
40
+ * caller look like the same person, so this refuses instead of returning a
41
+ * value that reads as an identity.
42
+ */
43
+ export function requireUserId(actor: Pick<Actor, "userId"> | null): string {
44
+ if (!actor) {
45
+ throw new CommerceForbiddenError("Authentication required.");
46
+ }
47
+ if (!actor.userId) {
48
+ throw new CommerceForbiddenError("This action requires a signed-in user.");
49
+ }
50
+ return actor.userId;
51
+ }
@@ -0,0 +1,107 @@
1
+ import type { CommerceConfig } from "../config/types.js";
2
+
3
+ const BUILTIN_ROLE_RANK: Record<string, number> = {
4
+ owner: 3,
5
+ admin: 2,
6
+ };
7
+ const CUSTOM_ROLE_RANK = 1;
8
+
9
+ /**
10
+ * Who may grant which role.
11
+ *
12
+ * Every surface that mints or changes a membership answers this question, and
13
+ * they must all answer it the same way — the admin staff routes, and the guard
14
+ * in front of Better Auth's organization endpoints. Red-team round 6 found the
15
+ * takeover that follows from two surfaces disagreeing, so the arithmetic lives
16
+ * here and nowhere else.
17
+ */
18
+
19
+ /**
20
+ * Better Auth stores a member's role as a comma-separated list, so `"owner"`
21
+ * and `"owner,admin"` are both owners to it. Commerce role lookups are exact
22
+ * string matches, which is how a composite string used to read as an unknown
23
+ * custom role on one side and an owner on the other.
24
+ */
25
+ export function roleParts(role: string | null | undefined): string[] {
26
+ return (role ?? "")
27
+ .split(",")
28
+ .map((part) => part.trim())
29
+ .filter((part) => part.length > 0);
30
+ }
31
+
32
+ export function isCompositeRole(role: string | null | undefined): boolean {
33
+ return roleParts(role).length > 1;
34
+ }
35
+
36
+ /** True when any part of the role string is `owner`, matching Better Auth. */
37
+ export function isOwnerRole(role: string | null | undefined): boolean {
38
+ return roleParts(role).includes("owner");
39
+ }
40
+
41
+ export function permissionsForRole(config: CommerceConfig, role: string): string[] {
42
+ return config.auth?.roles?.[role]?.permissions ?? [];
43
+ }
44
+
45
+ export function hasPermissionFromList(
46
+ actorPermissions: readonly string[],
47
+ required: string,
48
+ ): boolean {
49
+ if (actorPermissions.includes("*:*")) return true;
50
+
51
+ const [resource] = required.split(":");
52
+ if (resource && actorPermissions.includes(`${resource}:*`)) return true;
53
+ return actorPermissions.includes(required);
54
+ }
55
+
56
+ /**
57
+ * The role's privilege rank. A composite role ranks as its strongest part, so
58
+ * `"owner,admin"` cannot slip past a rank floor by failing an exact lookup.
59
+ */
60
+ export function roleRank(config: CommerceConfig, role: string | null | undefined): number {
61
+ const ranks = roleParts(role).map((part) => {
62
+ const builtin = BUILTIN_ROLE_RANK[part];
63
+ if (builtin !== undefined) return builtin;
64
+ if (permissionsForRole(config, part).includes("*:*")) return BUILTIN_ROLE_RANK["admin"]!;
65
+ return CUSTOM_ROLE_RANK;
66
+ });
67
+ return ranks.length > 0 ? Math.max(...ranks) : CUSTOM_ROLE_RANK;
68
+ }
69
+
70
+ export interface Granter {
71
+ role: string;
72
+ permissions: readonly string[];
73
+ }
74
+
75
+ /**
76
+ * A granter may assign `targetRole` only when it already holds every permission
77
+ * that role carries (containment) and outranks or equals it (rank floor).
78
+ */
79
+ export function canGrantRole(
80
+ config: CommerceConfig,
81
+ granter: Granter | null,
82
+ targetRole: string,
83
+ ): boolean {
84
+ if (!granter) return false;
85
+ const contains = permissionsForRole(config, targetRole).every((permission) =>
86
+ hasPermissionFromList(granter.permissions, permission),
87
+ );
88
+ return contains && roleRank(config, granter.role) >= roleRank(config, targetRole);
89
+ }
90
+
91
+ /**
92
+ * The granter a stored membership row represents. Permissions come from the
93
+ * role's current definition, which is the whole point of re-checking authority
94
+ * later: the row is re-read, not the authority the actor had when they acted.
95
+ */
96
+ export function granterForRole(config: CommerceConfig, role: string): Granter {
97
+ return { role, permissions: permissionsForRole(config, role) };
98
+ }
99
+
100
+ export function validRoles(config: CommerceConfig): Set<string> {
101
+ return new Set([
102
+ ...Object.keys(config.auth?.roles ?? {}),
103
+ "owner",
104
+ "admin",
105
+ "member",
106
+ ]);
107
+ }
package/src/auth/setup.ts CHANGED
@@ -65,6 +65,23 @@ export function createAuth(
65
65
  | ReturnType<typeof jwt>
66
66
  | ReturnType<typeof bearer>
67
67
  > = [
68
+ // These are commerce permission arrays, not Better Auth access-control
69
+ // `Role` objects exposing `.authorize()`. Its organization plugin therefore
70
+ // cannot evaluate a permission with them, and every check reaching its
71
+ // authorize loop throws instead of deciding — fail-closed, but by type
72
+ // confusion rather than by intent.
73
+ //
74
+ // That is deliberate and stays. This repository does not use Better Auth's
75
+ // access-control model: `admin/staff.ts` is the governed membership
76
+ // surface, and `auth/role-authority.ts` holds the arithmetic. Handing the
77
+ // plugin real `Role` objects would stand up a second permission model to
78
+ // keep in agreement with the first, which is how the two layers disagreed
79
+ // about composite roles and owner counting in the first place.
80
+ //
81
+ // What must not be relied on is the throw. `auth/organization-guard.ts`
82
+ // refuses the plugin's membership writers outright, so repairing this
83
+ // wiring cannot turn an accidental closure into an open door. Pin that
84
+ // guard's test before changing anything here.
68
85
  organization({
69
86
  roles: (config.auth?.roles ?? {}) as unknown as Record<string, Role | undefined>,
70
87
  }),
@@ -7,8 +7,14 @@ export function setBootStrictOrgResolution(strict: boolean): void {
7
7
  }
8
8
 
9
9
  export function isStrictOrgResolution(config?: CommerceConfig | null): boolean {
10
+ // Fail closed by default. Without an actor there is no tenant, and silently
11
+ // resolving to a default organization served one merchant's data to
12
+ // unauthenticated callers on every unguarded or allowlisted read path.
13
+ // Single-tenant deployments that relied on that fallback opt out explicitly.
14
+ if (config?.auth?.strictOrgResolution === false) return false;
15
+ if (process.env.STRICT_ORG_RESOLUTION === "false") return false;
10
16
  if (config?.auth?.strictOrgResolution === true) return true;
11
17
  if (process.env.STRICT_ORG_RESOLUTION === "true") return true;
12
18
  if ((config === undefined || config === null) && _bootStrictOrgResolution) return true;
13
- return false;
19
+ return true;
14
20
  }
package/src/auth/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export interface Actor {
2
2
  type: "user" | "api_key";
3
- userId: string;
3
+ userId: string | null;
4
4
  email: string | null;
5
5
  name: string;
6
6
  vendorId: string | null;
@@ -24,10 +24,12 @@ export const defaultConfig: Partial<CommerceConfig> = {
24
24
  "catalog:update",
25
25
  "catalog:delete",
26
26
  "catalog:read",
27
+ "catalog:read:unpublished",
27
28
  "inventory:read",
28
29
  "inventory:adjust",
29
30
  "orders:read",
30
31
  "orders:create",
32
+ "orders:create:on-behalf",
31
33
  "orders:update",
32
34
  "orders:manage",
33
35
  "cart:create",
@@ -200,10 +200,17 @@ export interface AuthConfig {
200
200
  */
201
201
  storeResolver?: (request: Request) => string | null | Promise<string | null>;
202
202
  /**
203
- * When true, a failing `storeResolver` for anonymous requests returns HTTP 503
204
- * instead of continuing with `actor = null` (legacy). Same behavior when env
205
- * `STRICT_ORG_RESOLUTION` is `"true"`. Default false keeps backward-compatible
206
- * fallback for single-store and lenient multi-store setups.
203
+ * Governs two layers, and its default differs between them.
204
+ *
205
+ * In the store-resolver middleware, `true` makes a failing `storeResolver`
206
+ * return HTTP 503 rather than continuing with `actor = null`; that layer
207
+ * still defaults to the lenient behaviour.
208
+ *
209
+ * In organization resolution it **fails closed by default**: an actor-less
210
+ * request with no explicit organization and no `defaultOrganizationId` is
211
+ * refused rather than served a fallback tenant. Set this to `false`, or the
212
+ * env var `STRICT_ORG_RESOLUTION` to `"false"`, to restore the old fallback
213
+ * during a migration.
207
214
  */
208
215
  strictOrgResolution?: boolean;
209
216
  /**
@@ -258,7 +265,25 @@ export interface CheckoutConfig {
258
265
  };
259
266
  }
260
267
 
268
+ /**
269
+ * Decides whether a guest bearer credential (a cart secret) may still read a
270
+ * placed order. The authenticated customer who owns an order is never subject
271
+ * to this — ownership grants permanent access.
272
+ *
273
+ * Modelled on Vendure's `OrderByCodeAccessStrategy`: the value of the seam is
274
+ * that the policy has one home, rather than being an emergent property of the
275
+ * read path.
276
+ */
277
+ export interface GuestOrderAccessStrategy {
278
+ canAccessOrder(order: { placedAt: Date }, now: Date): boolean;
279
+ }
280
+
261
281
  export interface OrdersConfig {
282
+ /**
283
+ * How long a guest cart secret keeps reading an order after placement.
284
+ * Defaults to `windowedGuestOrderAccess("7d")`.
285
+ */
286
+ guestAccessStrategy?: GuestOrderAccessStrategy;
262
287
  hooks?: {
263
288
  beforeCreate?: BeforeHook<unknown>[];
264
289
  afterCreate?: AfterHook<unknown>[];
@@ -1,5 +1,5 @@
1
1
  import { CommerceValidationError } from "../kernel/errors.js";
2
- import { resolveOrgId } from "../auth/org.js";
2
+ import { resolveOrgIdForCommerce } from "../auth/org.js";
3
3
  import type { CompensationFailuresRepository } from "../kernel/compensation/repository.js";
4
4
  import type { AfterHook, BeforeHook } from "../kernel/hooks/types.js";
5
5
  import type { ShippingAddress } from "../modules/shipping/calculator.js";
@@ -97,7 +97,7 @@ export const validateCartNotEmpty: BeforeHook<CheckoutData> = async ({
97
97
  context,
98
98
  }) => {
99
99
  const cartService = context.services.cart as {
100
- getById(id: string, actor?: unknown): Promise<
100
+ getByIdForInternalUse(id: string, organizationId: string, ctx?: TxContext): Promise<
101
101
  | {
102
102
  ok: true;
103
103
  value: {
@@ -114,7 +114,7 @@ export const validateCartNotEmpty: BeforeHook<CheckoutData> = async ({
114
114
  }
115
115
  | { ok: false }
116
116
  >;
117
- claimForCheckout(cartId: string, ctx?: unknown): Promise<
117
+ claimForCheckout(cartId: string, claimToken: string, ctx?: unknown): Promise<
118
118
  | { ok: true; value: { id: string } }
119
119
  | { ok: false; error: { message: string } }
120
120
  >;
@@ -122,7 +122,9 @@ export const validateCartNotEmpty: BeforeHook<CheckoutData> = async ({
122
122
  const catalogService = context.services.catalog as {
123
123
  getById(
124
124
  id: string,
125
- options?: { includeAttributes?: boolean },
125
+ options: { includeAttributes?: boolean } | undefined,
126
+ actor: unknown,
127
+ ctx?: TxContext,
126
128
  ): Promise<
127
129
  | {
128
130
  ok: true;
@@ -137,20 +139,25 @@ export const validateCartNotEmpty: BeforeHook<CheckoutData> = async ({
137
139
 
138
140
  // M1 fix: Atomically claim the cart for checkout (active → checking_out).
139
141
  // If a concurrent request already claimed it, this returns Err and we fail fast.
140
- const claimed = await cartService.claimForCheckout(data.cartId, context.tx);
142
+ // The checkout id is the claim token, so only this attempt can release it.
143
+ const claimed = await cartService.claimForCheckout(data.cartId, data.checkoutId, context.tx);
141
144
  if (!claimed.ok) {
142
145
  throw new CommerceValidationError(
143
146
  "Cart is not available for checkout. It may have already been checked out by a concurrent request.",
144
147
  );
145
148
  }
146
149
 
147
- const cart = await cartService.getById(data.cartId, context.actor);
150
+ const cart = await cartService.getByIdForInternalUse(
151
+ data.cartId,
152
+ resolveOrgIdForCommerce(context.actor, context.commerceConfig),
153
+ context.tx as TxContext | undefined,
154
+ );
148
155
  if (!cart.ok || cart.value.lineItems.length === 0) {
149
156
  throw new CommerceValidationError("Cannot checkout an empty cart.");
150
157
  }
151
158
 
152
159
  // Cross-org guard: prevent org B from checking out org A's cart
153
- const actorOrgId = resolveOrgId(context.actor);
160
+ const actorOrgId = resolveOrgIdForCommerce(context.actor, context.commerceConfig);
154
161
  if (cart.value.organizationId && cart.value.organizationId !== actorOrgId) {
155
162
  throw new CommerceValidationError("Cart does not belong to this organization.");
156
163
  }
@@ -174,7 +181,7 @@ export const validateCartNotEmpty: BeforeHook<CheckoutData> = async ({
174
181
  cart.value.lineItems.map(async (item) => {
175
182
  const entity = await catalogService.getById(item.entityId, {
176
183
  includeAttributes: true,
177
- });
184
+ }, context.actor, context.tx as TxContext | undefined);
178
185
  const title = entity.ok
179
186
  ? (entity.value.attributes?.[0]?.title ?? item.entityId)
180
187
  : item.entityId;
@@ -323,7 +330,7 @@ export const applyPromotionCodes: BeforeHook<CheckoutData> = async ({
323
330
  };
324
331
 
325
332
  const result = await promotions.applyPromotions({
326
- orgId: resolveOrgId(context.actor),
333
+ orgId: resolveOrgIdForCommerce(context.actor, context.commerceConfig),
327
334
  cartId: data.cartId,
328
335
  currency: data.currency,
329
336
  subtotal: data.subtotal,
@@ -411,7 +418,7 @@ export const calculateTax: BeforeHook<CheckoutData> = async ({
411
418
  ...(data.shippingAddress !== undefined
412
419
  ? { toAddress: data.shippingAddress }
413
420
  : {}),
414
- }, resolveOrgId(context.actor ?? null));
421
+ }, resolveOrgIdForCommerce(context.actor ?? null, context.commerceConfig));
415
422
 
416
423
  if (!calculated.ok) {
417
424
  throw new CommerceValidationError(
@@ -469,7 +476,7 @@ export const calculateShipping: BeforeHook<CheckoutData> = async ({
469
476
  })),
470
477
  subtotalAfterDiscount: Math.max(0, data.subtotal - data.discountTotal),
471
478
  currency: data.currency,
472
- orgId: resolveOrgId(context.actor ?? null),
479
+ orgId: resolveOrgIdForCommerce(context.actor ?? null, context.commerceConfig),
473
480
  ...(data.shippingAddress !== undefined
474
481
  ? { address: data.shippingAddress }
475
482
  : {}),
@@ -546,7 +553,7 @@ export const authorizePayment: BeforeHook<CheckoutData> = async ({
546
553
  : {}),
547
554
  metadata: {
548
555
  ...(data.orderId !== undefined ? { orderId: data.orderId } : {}),
549
- organizationId: resolveOrgId(context.actor),
556
+ organizationId: resolveOrgIdForCommerce(context.actor, context.commerceConfig),
550
557
  checkoutId: data.checkoutId,
551
558
  cartId: data.cartId,
552
559
  },
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ export type {
3
3
  CommerceConfig,
4
4
  CommercePlugin,
5
5
  ApiKeyScopeDefinition,
6
+ GuestOrderAccessStrategy,
6
7
  } from "./config/types.js";
7
8
  export { defineCommercePlugin } from "./kernel/plugin/manifest.js";
8
9
  export type {
@@ -31,12 +32,12 @@ export type { Kernel } from "./runtime/kernel.js";
31
32
  // This avoids pulling drizzle-kit/tsx/esbuild into Turbopack's bundle graph.
32
33
 
33
34
  export type { Actor } from "./auth/types.js";
34
- export { resolveOrgId, ensureDefaultOrg, DEFAULT_ORG_ID } from "./auth/org.js";
35
+ export { resolveOrgId, resolveOrgIdForCommerce, ensureDefaultOrg, DEFAULT_ORG_ID } from "./auth/org.js";
35
36
  export { createSystemActor } from "./auth/system-actor.js";
36
37
  export { OrganizationService } from "./modules/organization/service.js";
37
38
  export { createScopedDb } from "./kernel/database/scoped-db.js";
38
39
  export type { ScopedOrganizationId } from "./kernel/database/scoped-db.js";
39
- export { assertOwnership, assertPermission } from "./auth/permissions.js";
40
+ export { assertOwnership, assertPermission, requireUserId } from "./auth/permissions.js";
40
41
  export type { AccessResult, AccessContext, AccessFn, WhereClause } from "./auth/access.js";
41
42
  export {
42
43
  accessOR,
@@ -183,14 +184,18 @@ export type {
183
184
  export type { DatabaseAdapter } from "./kernel/database/adapter.js";
184
185
  export { isValidFieldPath, validateFieldPath } from "./modules/catalog/ownership.js";
185
186
  export type { FieldPath, FieldOwner } from "./modules/catalog/ownership.js";
187
+ export type {
188
+ TxContext,
189
+ WithTransactionOptions,
190
+ CatalogWriteContext,
191
+ HookContextCarrier,
192
+ } from "./kernel/database/tx-context.js";
186
193
  export {
187
194
  createTxContext,
188
195
  reuseOrCreateTxContext,
189
196
  withTransaction,
190
- } from "./kernel/database/tx-context.js";
191
- export type {
192
- TxContext,
193
- WithTransactionOptions,
197
+ isWriteContextTransactional,
198
+ resolveWriteContextHookContext,
194
199
  } from "./kernel/database/tx-context.js";
195
200
  export type {
196
201
  TaxAdapter,
@@ -249,6 +254,11 @@ export type { QueryInput, QueryResult } from "./kernel/query/executor.js";
249
254
  export type { CommerceModuleTypes } from "./types/commerce-types.js";
250
255
 
251
256
  export { staleOrderCleanupTask } from "./modules/orders/stale-order-cleanup.js";
257
+ export {
258
+ windowedGuestOrderAccess,
259
+ defaultGuestOrderAccess,
260
+ parseAccessWindow,
261
+ } from "./modules/orders/guest-access.js";
252
262
  export { COMMERCE_AGENT_SYSTEM_PROMPT } from "./utils/agent-prompt.js";
253
263
 
254
264
  export { DrizzleAnalyticsAdapter } from "./modules/analytics/drizzle-adapter.js";
@@ -95,12 +95,14 @@ export function auditMiddleware(kernel: Kernel): MiddlewareHandler {
95
95
  try {
96
96
  const requestId = c.get("requestId") as string | undefined;
97
97
  const ctx = createHookContext({
98
+ // Anonymous audit records retain actor: null; organization comes from the deployment config.
98
99
  actor: (c.get("actor") as Actor | null) ?? null,
99
100
  ...(requestId ? { requestId } : {}),
100
101
  logger: kernel.logger,
101
102
  services: kernel.services as unknown as ServiceContainer,
102
103
  database: { db: kernel.database.db as unknown as PluginDb },
103
104
  origin: "rest",
105
+ commerceConfig: kernel.config,
104
106
  });
105
107
  await kernel.services.audit.record({ entityType, entityId, event, payload, ctx });
106
108
  } catch {