@c15t/backend 2.0.0-rc.4 → 2.0.0-rc.6

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 (327) hide show
  1. package/dist/302.js +473 -0
  2. package/dist/364.js +1140 -0
  3. package/dist/583.js +540 -0
  4. package/dist/cache.cjs +1 -1
  5. package/dist/cache.js +4 -415
  6. package/dist/core.cjs +849 -96
  7. package/dist/core.js +147 -1817
  8. package/dist/db/adapters/drizzle.cjs +1 -1
  9. package/dist/db/adapters/drizzle.js +1 -2
  10. package/dist/db/adapters/kysely.cjs +1 -1
  11. package/dist/db/adapters/kysely.js +1 -2
  12. package/dist/db/adapters/mongo.cjs +1 -1
  13. package/dist/db/adapters/mongo.js +1 -2
  14. package/dist/db/adapters/prisma.cjs +1 -1
  15. package/dist/db/adapters/prisma.js +1 -2
  16. package/dist/db/adapters/typeorm.cjs +1 -1
  17. package/dist/db/adapters/typeorm.js +1 -2
  18. package/dist/db/adapters.cjs +1 -1
  19. package/dist/db/migrator.cjs +1 -1
  20. package/dist/db/schema.cjs +38 -1
  21. package/dist/db/schema.js +33 -2
  22. package/dist/define-config.cjs +1 -1
  23. package/dist/edge.cjs +1106 -0
  24. package/dist/edge.js +190 -0
  25. package/dist/router.cjs +629 -81
  26. package/dist/router.js +1 -1509
  27. package/dist/types/index.cjs +1 -1
  28. package/{dist → dist-types}/cache/adapters/cloudflare-kv.d.ts +0 -1
  29. package/{dist → dist-types}/cache/adapters/index.d.ts +0 -1
  30. package/{dist → dist-types}/cache/adapters/memory.d.ts +0 -1
  31. package/{dist → dist-types}/cache/adapters/upstash-redis.d.ts +0 -1
  32. package/{dist → dist-types}/cache/gvl-resolver.d.ts +1 -2
  33. package/{dist → dist-types}/cache/index.d.ts +0 -1
  34. package/{dist → dist-types}/cache/keys.d.ts +0 -1
  35. package/{dist → dist-types}/cache/types.d.ts +0 -1
  36. package/{dist → dist-types}/core.d.ts +8 -1
  37. package/{dist → dist-types}/db/migrator/index.d.ts +0 -1
  38. package/{dist → dist-types}/db/registry/consent-policy.d.ts +0 -1
  39. package/{dist → dist-types}/db/registry/consent-purpose.d.ts +0 -1
  40. package/{dist → dist-types}/db/registry/domain.d.ts +0 -1
  41. package/{dist → dist-types}/db/registry/index.d.ts +22 -2
  42. package/dist-types/db/registry/runtime-policy-decision.d.ts +60 -0
  43. package/{dist → dist-types}/db/registry/subject.d.ts +0 -1
  44. package/{dist → dist-types}/db/registry/types.d.ts +1 -2
  45. package/{dist → dist-types}/db/registry/utils/generate-id.d.ts +0 -1
  46. package/{dist → dist-types}/db/registry/utils.d.ts +0 -1
  47. package/{dist → dist-types}/db/schema/1.0.0/audit-log.d.ts +0 -1
  48. package/{dist → dist-types}/db/schema/1.0.0/consent-policy.d.ts +0 -1
  49. package/{dist → dist-types}/db/schema/1.0.0/consent-purpose.d.ts +0 -1
  50. package/{dist → dist-types}/db/schema/1.0.0/consent-record.d.ts +0 -1
  51. package/{dist → dist-types}/db/schema/1.0.0/consent.d.ts +2 -3
  52. package/{dist → dist-types}/db/schema/1.0.0/domain.d.ts +0 -1
  53. package/{dist → dist-types}/db/schema/1.0.0/index.d.ts +0 -1
  54. package/{dist → dist-types}/db/schema/1.0.0/subject.d.ts +0 -1
  55. package/{dist → dist-types}/db/schema/2.0.0/audit-log.d.ts +2 -3
  56. package/{dist → dist-types}/db/schema/2.0.0/consent-policy.d.ts +2 -3
  57. package/{dist → dist-types}/db/schema/2.0.0/consent-purpose.d.ts +2 -3
  58. package/{dist → dist-types}/db/schema/2.0.0/consent.d.ts +6 -3
  59. package/{dist → dist-types}/db/schema/2.0.0/domain.d.ts +2 -3
  60. package/{dist → dist-types}/db/schema/2.0.0/index.d.ts +432 -17
  61. package/dist-types/db/schema/2.0.0/runtime-policy-decision.d.ts +23 -0
  62. package/{dist → dist-types}/db/schema/2.0.0/subject.d.ts +2 -3
  63. package/{dist → dist-types}/db/schema/index.d.ts +862 -33
  64. package/{dist → dist-types}/db/tenant-scope.d.ts +0 -1
  65. package/{dist → dist-types}/define-config.d.ts +0 -1
  66. package/dist-types/edge/index.d.ts +5 -0
  67. package/dist-types/edge/init-handler.d.ts +38 -0
  68. package/dist-types/edge/resolve-consent.d.ts +80 -0
  69. package/dist-types/edge/types.d.ts +13 -0
  70. package/{dist → dist-types}/handlers/consent/check.handler.d.ts +0 -1
  71. package/{src/handlers/consent/index.ts → dist-types/handlers/consent/index.d.ts} +0 -1
  72. package/{dist → dist-types}/handlers/init/geo.d.ts +2 -3
  73. package/{dist → dist-types}/handlers/init/index.d.ts +4 -5
  74. package/dist-types/handlers/init/policy.d.ts +26 -0
  75. package/dist-types/handlers/init/resolve-init.d.ts +44 -0
  76. package/dist-types/handlers/init/translations.d.ts +48 -0
  77. package/dist-types/handlers/policy/snapshot.d.ts +99 -0
  78. package/{src/handlers/status/index.ts → dist-types/handlers/status/index.d.ts} +0 -1
  79. package/{dist → dist-types}/handlers/status/status.handler.d.ts +0 -1
  80. package/{dist → dist-types}/handlers/subject/get.handler.d.ts +0 -1
  81. package/{src/handlers/subject/index.ts → dist-types/handlers/subject/index.d.ts} +0 -1
  82. package/{dist → dist-types}/handlers/subject/list.handler.d.ts +0 -1
  83. package/{dist → dist-types}/handlers/subject/patch.handler.d.ts +0 -1
  84. package/{dist → dist-types}/handlers/subject/post.handler.d.ts +12 -1
  85. package/{dist → dist-types}/handlers/utils/consent-enrichment.d.ts +0 -1
  86. package/{dist → dist-types}/init.d.ts +0 -1
  87. package/{dist → dist-types}/middleware/auth/index.d.ts +0 -1
  88. package/{dist → dist-types}/middleware/auth/validate-api-key.d.ts +0 -1
  89. package/{dist → dist-types}/middleware/cors/cors.d.ts +0 -1
  90. package/{src/middleware/cors/index.ts → dist-types/middleware/cors/index.d.ts} +0 -1
  91. package/{dist → dist-types}/middleware/cors/is-origin-trusted.d.ts +1 -2
  92. package/{dist → dist-types}/middleware/cors/process-cors.d.ts +0 -1
  93. package/{dist → dist-types}/middleware/openapi/config.d.ts +0 -1
  94. package/{dist → dist-types}/middleware/openapi/handlers.d.ts +0 -1
  95. package/{src/middleware/openapi/index.ts → dist-types/middleware/openapi/index.d.ts} +0 -1
  96. package/{dist → dist-types}/middleware/process-ip/index.d.ts +0 -1
  97. package/dist-types/policies/builder.d.ts +127 -0
  98. package/dist-types/policies/defaults.d.ts +2 -0
  99. package/dist-types/policies/matchers.d.ts +3 -0
  100. package/{dist → dist-types}/router.d.ts +0 -1
  101. package/{dist → dist-types}/routes/consent.d.ts +0 -1
  102. package/{src/routes/index.ts → dist-types/routes/index.d.ts} +0 -1
  103. package/{dist → dist-types}/routes/init.d.ts +0 -1
  104. package/{dist → dist-types}/routes/status.d.ts +0 -1
  105. package/{dist → dist-types}/routes/subject.d.ts +0 -1
  106. package/{dist → dist-types}/types/api.d.ts +0 -1
  107. package/{dist → dist-types}/types/index.d.ts +110 -6
  108. package/dist-types/utils/background.d.ts +6 -0
  109. package/{dist → dist-types}/utils/create-telemetry-options.d.ts +0 -1
  110. package/{dist → dist-types}/utils/env.d.ts +0 -1
  111. package/{dist → dist-types}/utils/extract-error-message.d.ts +0 -1
  112. package/{dist → dist-types}/utils/instrumentation.d.ts +0 -1
  113. package/{dist → dist-types}/utils/logger.d.ts +1 -2
  114. package/{dist → dist-types}/utils/metrics.d.ts +0 -1
  115. package/dist-types/version.d.ts +1 -0
  116. package/docs/README.md +49 -0
  117. package/docs/api/configuration.md +197 -0
  118. package/docs/api/endpoints.md +211 -0
  119. package/docs/guides/caching.md +85 -0
  120. package/docs/guides/database-setup.md +128 -0
  121. package/docs/guides/edge-deployment.md +248 -0
  122. package/docs/guides/framework-integration.md +142 -0
  123. package/docs/guides/iab-tcf.md +89 -0
  124. package/docs/guides/observability.md +96 -0
  125. package/docs/guides/policy-packs.md +396 -0
  126. package/docs/quickstart.md +129 -0
  127. package/package.json +45 -31
  128. package/.turbo/turbo-build.log +0 -49
  129. package/CHANGELOG.md +0 -123
  130. package/dist/cache/adapters/cloudflare-kv.d.ts.map +0 -1
  131. package/dist/cache/adapters/index.d.ts.map +0 -1
  132. package/dist/cache/adapters/memory.d.ts.map +0 -1
  133. package/dist/cache/adapters/upstash-redis.d.ts.map +0 -1
  134. package/dist/cache/gvl-resolver.d.ts.map +0 -1
  135. package/dist/cache/index.d.ts.map +0 -1
  136. package/dist/cache/keys.d.ts.map +0 -1
  137. package/dist/cache/types.d.ts.map +0 -1
  138. package/dist/core.d.ts.map +0 -1
  139. package/dist/db/adapters/drizzle.d.ts +0 -2
  140. package/dist/db/adapters/drizzle.d.ts.map +0 -1
  141. package/dist/db/adapters/index.d.ts +0 -2
  142. package/dist/db/adapters/index.d.ts.map +0 -1
  143. package/dist/db/adapters/kysely.d.ts +0 -2
  144. package/dist/db/adapters/kysely.d.ts.map +0 -1
  145. package/dist/db/adapters/mongo.d.ts +0 -2
  146. package/dist/db/adapters/mongo.d.ts.map +0 -1
  147. package/dist/db/adapters/prisma.d.ts +0 -2
  148. package/dist/db/adapters/prisma.d.ts.map +0 -1
  149. package/dist/db/adapters/typeorm.d.ts +0 -2
  150. package/dist/db/adapters/typeorm.d.ts.map +0 -1
  151. package/dist/db/migrator/index.d.ts.map +0 -1
  152. package/dist/db/registry/consent-policy.d.ts.map +0 -1
  153. package/dist/db/registry/consent-purpose.d.ts.map +0 -1
  154. package/dist/db/registry/domain.d.ts.map +0 -1
  155. package/dist/db/registry/index.d.ts.map +0 -1
  156. package/dist/db/registry/subject.d.ts.map +0 -1
  157. package/dist/db/registry/types.d.ts.map +0 -1
  158. package/dist/db/registry/utils/generate-id.d.ts.map +0 -1
  159. package/dist/db/registry/utils.d.ts.map +0 -1
  160. package/dist/db/schema/1.0.0/audit-log.d.ts.map +0 -1
  161. package/dist/db/schema/1.0.0/consent-policy.d.ts.map +0 -1
  162. package/dist/db/schema/1.0.0/consent-purpose.d.ts.map +0 -1
  163. package/dist/db/schema/1.0.0/consent-record.d.ts.map +0 -1
  164. package/dist/db/schema/1.0.0/consent.d.ts.map +0 -1
  165. package/dist/db/schema/1.0.0/domain.d.ts.map +0 -1
  166. package/dist/db/schema/1.0.0/index.d.ts.map +0 -1
  167. package/dist/db/schema/1.0.0/subject.d.ts.map +0 -1
  168. package/dist/db/schema/2.0.0/audit-log.d.ts.map +0 -1
  169. package/dist/db/schema/2.0.0/consent-policy.d.ts.map +0 -1
  170. package/dist/db/schema/2.0.0/consent-purpose.d.ts.map +0 -1
  171. package/dist/db/schema/2.0.0/consent.d.ts.map +0 -1
  172. package/dist/db/schema/2.0.0/domain.d.ts.map +0 -1
  173. package/dist/db/schema/2.0.0/index.d.ts.map +0 -1
  174. package/dist/db/schema/2.0.0/subject.d.ts.map +0 -1
  175. package/dist/db/schema/index.d.ts.map +0 -1
  176. package/dist/db/tenant-scope.d.ts.map +0 -1
  177. package/dist/define-config.d.ts.map +0 -1
  178. package/dist/handlers/consent/check.handler.d.ts.map +0 -1
  179. package/dist/handlers/consent/index.d.ts +0 -12
  180. package/dist/handlers/consent/index.d.ts.map +0 -1
  181. package/dist/handlers/init/geo.d.ts.map +0 -1
  182. package/dist/handlers/init/index.d.ts.map +0 -1
  183. package/dist/handlers/init/translations.d.ts +0 -26
  184. package/dist/handlers/init/translations.d.ts.map +0 -1
  185. package/dist/handlers/status/index.d.ts +0 -7
  186. package/dist/handlers/status/index.d.ts.map +0 -1
  187. package/dist/handlers/status/status.handler.d.ts.map +0 -1
  188. package/dist/handlers/subject/get.handler.d.ts.map +0 -1
  189. package/dist/handlers/subject/index.d.ts +0 -10
  190. package/dist/handlers/subject/index.d.ts.map +0 -1
  191. package/dist/handlers/subject/list.handler.d.ts.map +0 -1
  192. package/dist/handlers/subject/patch.handler.d.ts.map +0 -1
  193. package/dist/handlers/subject/post.handler.d.ts.map +0 -1
  194. package/dist/handlers/utils/consent-enrichment.d.ts.map +0 -1
  195. package/dist/init.d.ts.map +0 -1
  196. package/dist/middleware/auth/index.d.ts.map +0 -1
  197. package/dist/middleware/auth/validate-api-key.d.ts.map +0 -1
  198. package/dist/middleware/cors/cors.d.ts.map +0 -1
  199. package/dist/middleware/cors/index.d.ts +0 -30
  200. package/dist/middleware/cors/index.d.ts.map +0 -1
  201. package/dist/middleware/cors/is-origin-trusted.d.ts.map +0 -1
  202. package/dist/middleware/cors/process-cors.d.ts.map +0 -1
  203. package/dist/middleware/openapi/config.d.ts.map +0 -1
  204. package/dist/middleware/openapi/handlers.d.ts.map +0 -1
  205. package/dist/middleware/openapi/index.d.ts +0 -12
  206. package/dist/middleware/openapi/index.d.ts.map +0 -1
  207. package/dist/middleware/process-ip/index.d.ts.map +0 -1
  208. package/dist/router.d.ts.map +0 -1
  209. package/dist/routes/consent.d.ts.map +0 -1
  210. package/dist/routes/index.d.ts +0 -10
  211. package/dist/routes/index.d.ts.map +0 -1
  212. package/dist/routes/init.d.ts.map +0 -1
  213. package/dist/routes/status.d.ts.map +0 -1
  214. package/dist/routes/subject.d.ts.map +0 -1
  215. package/dist/types/api.d.ts.map +0 -1
  216. package/dist/types/index.d.ts.map +0 -1
  217. package/dist/utils/create-telemetry-options.d.ts.map +0 -1
  218. package/dist/utils/env.d.ts.map +0 -1
  219. package/dist/utils/extract-error-message.d.ts.map +0 -1
  220. package/dist/utils/index.d.ts +0 -4
  221. package/dist/utils/index.d.ts.map +0 -1
  222. package/dist/utils/instrumentation.d.ts.map +0 -1
  223. package/dist/utils/logger.d.ts.map +0 -1
  224. package/dist/utils/metrics.d.ts.map +0 -1
  225. package/dist/version.d.ts +0 -2
  226. package/dist/version.d.ts.map +0 -1
  227. package/knip.json +0 -31
  228. package/rslib.config.ts +0 -93
  229. package/src/cache/adapters/cloudflare-kv.ts +0 -71
  230. package/src/cache/adapters/index.ts +0 -22
  231. package/src/cache/adapters/memory.ts +0 -111
  232. package/src/cache/adapters/upstash-redis.ts +0 -113
  233. package/src/cache/gvl-resolver.ts +0 -289
  234. package/src/cache/index.ts +0 -34
  235. package/src/cache/keys.ts +0 -68
  236. package/src/cache/types.ts +0 -66
  237. package/src/core.ts +0 -369
  238. package/src/db/migrator/index.ts +0 -80
  239. package/src/db/registry/consent-policy.test.ts +0 -451
  240. package/src/db/registry/consent-policy.ts +0 -82
  241. package/src/db/registry/consent-purpose.test.ts +0 -428
  242. package/src/db/registry/consent-purpose.ts +0 -61
  243. package/src/db/registry/domain.test.ts +0 -445
  244. package/src/db/registry/domain.ts +0 -91
  245. package/src/db/registry/index.ts +0 -14
  246. package/src/db/registry/subject.test.ts +0 -371
  247. package/src/db/registry/subject.ts +0 -126
  248. package/src/db/registry/types.ts +0 -10
  249. package/src/db/registry/utils/generate-id.test.ts +0 -216
  250. package/src/db/registry/utils/generate-id.ts +0 -133
  251. package/src/db/registry/utils.ts +0 -133
  252. package/src/db/schema/1.0.0/audit-log.ts +0 -15
  253. package/src/db/schema/1.0.0/consent-policy.ts +0 -14
  254. package/src/db/schema/1.0.0/consent-purpose.ts +0 -14
  255. package/src/db/schema/1.0.0/consent-record.ts +0 -10
  256. package/src/db/schema/1.0.0/consent.ts +0 -20
  257. package/src/db/schema/1.0.0/domain.ts +0 -12
  258. package/src/db/schema/1.0.0/index.ts +0 -48
  259. package/src/db/schema/1.0.0/subject.ts +0 -11
  260. package/src/db/schema/2.0.0/audit-log.ts +0 -18
  261. package/src/db/schema/2.0.0/consent-policy.ts +0 -28
  262. package/src/db/schema/2.0.0/consent-purpose.ts +0 -12
  263. package/src/db/schema/2.0.0/consent.ts +0 -28
  264. package/src/db/schema/2.0.0/domain.ts +0 -12
  265. package/src/db/schema/2.0.0/index.ts +0 -47
  266. package/src/db/schema/2.0.0/subject.ts +0 -13
  267. package/src/db/schema/index.ts +0 -15
  268. package/src/db/tenant-scope.test.ts +0 -747
  269. package/src/db/tenant-scope.ts +0 -103
  270. package/src/define-config.ts +0 -19
  271. package/src/handlers/consent/check.handler.ts +0 -126
  272. package/src/handlers/init/geo.test.ts +0 -317
  273. package/src/handlers/init/geo.ts +0 -195
  274. package/src/handlers/init/index.test.ts +0 -205
  275. package/src/handlers/init/index.ts +0 -114
  276. package/src/handlers/init/translations.test.ts +0 -121
  277. package/src/handlers/init/translations.ts +0 -69
  278. package/src/handlers/status/status.handler.test.ts +0 -155
  279. package/src/handlers/status/status.handler.ts +0 -51
  280. package/src/handlers/subject/get.handler.ts +0 -92
  281. package/src/handlers/subject/list.handler.ts +0 -92
  282. package/src/handlers/subject/patch.handler.ts +0 -119
  283. package/src/handlers/subject/post.handler.test.ts +0 -294
  284. package/src/handlers/subject/post.handler.ts +0 -268
  285. package/src/handlers/utils/consent-enrichment.test.ts +0 -380
  286. package/src/handlers/utils/consent-enrichment.ts +0 -218
  287. package/src/init.test.ts +0 -122
  288. package/src/init.ts +0 -88
  289. package/src/middleware/auth/index.ts +0 -11
  290. package/src/middleware/auth/validate-api-key.test.ts +0 -86
  291. package/src/middleware/auth/validate-api-key.ts +0 -107
  292. package/src/middleware/cors/cors.test.ts +0 -135
  293. package/src/middleware/cors/cors.ts +0 -186
  294. package/src/middleware/cors/is-origin-trusted.test.ts +0 -164
  295. package/src/middleware/cors/is-origin-trusted.ts +0 -130
  296. package/src/middleware/cors/process-cors.ts +0 -91
  297. package/src/middleware/openapi/config.ts +0 -29
  298. package/src/middleware/openapi/handlers.ts +0 -34
  299. package/src/middleware/process-ip/index.test.ts +0 -193
  300. package/src/middleware/process-ip/index.ts +0 -199
  301. package/src/router.ts +0 -15
  302. package/src/routes/consent.ts +0 -52
  303. package/src/routes/init.ts +0 -105
  304. package/src/routes/status.ts +0 -46
  305. package/src/routes/subject.ts +0 -152
  306. package/src/types/api.ts +0 -48
  307. package/src/types/index.ts +0 -391
  308. package/src/utils/create-telemetry-options.test.ts +0 -286
  309. package/src/utils/create-telemetry-options.ts +0 -229
  310. package/src/utils/env.ts +0 -84
  311. package/src/utils/extract-error-message.ts +0 -21
  312. package/src/utils/instrumentation.test.ts +0 -183
  313. package/src/utils/instrumentation.ts +0 -194
  314. package/src/utils/logger.ts +0 -41
  315. package/src/utils/metrics.test.ts +0 -311
  316. package/src/utils/metrics.ts +0 -402
  317. package/src/utils/telemetry-pii.test.ts +0 -323
  318. package/src/version.ts +0 -2
  319. package/tsconfig.json +0 -11
  320. package/vitest.config.ts +0 -28
  321. /package/{src/db/adapters/drizzle.ts → dist-types/db/adapters/drizzle.d.ts} +0 -0
  322. /package/{src/db/adapters/index.ts → dist-types/db/adapters/index.d.ts} +0 -0
  323. /package/{src/db/adapters/kysely.ts → dist-types/db/adapters/kysely.d.ts} +0 -0
  324. /package/{src/db/adapters/mongo.ts → dist-types/db/adapters/mongo.d.ts} +0 -0
  325. /package/{src/db/adapters/prisma.ts → dist-types/db/adapters/prisma.d.ts} +0 -0
  326. /package/{src/db/adapters/typeorm.ts → dist-types/db/adapters/typeorm.d.ts} +0 -0
  327. /package/{src/utils/index.ts → dist-types/utils/index.d.ts} +0 -0
package/dist/router.js CHANGED
@@ -1,1509 +1 @@
1
- import { checkConsentOutputSchema, checkConsentQuerySchema, getSubjectInputSchema, getSubjectOutputSchema, initOutputSchema, listSubjectsOutputSchema, listSubjectsQuerySchema, patchSubjectOutputSchema, postSubjectInputSchema, postSubjectOutputSchema, statusOutputSchema, subjectIdSchema } from "@c15t/schema";
2
- import { Hono } from "hono";
3
- import { describeRoute, resolver, validator } from "hono-openapi";
4
- import { HTTPException } from "hono/http-exception";
5
- import { SpanKind as api_SpanKind, SpanStatusCode as api_SpanStatusCode, context, metrics as api_metrics, trace as api_trace } from "@opentelemetry/api";
6
- import { deepMergeTranslations, selectLanguage } from "@c15t/translations";
7
- import { baseTranslations } from "@c15t/translations/all";
8
- import { object, optional, string } from "valibot";
9
- import base_x from "base-x";
10
- function extractErrorMessage(error) {
11
- if (error instanceof AggregateError && error.errors?.length > 0) {
12
- const inner = error.errors.map((e)=>e instanceof Error ? e.message : String(e)).join('; ');
13
- return `AggregateError: ${inner}`;
14
- }
15
- if (error instanceof Error) return error.message || error.name;
16
- return String(error);
17
- }
18
- const version_version = '2.0.0-rc.4';
19
- let cachedConfig = null;
20
- let cachedDefaultAttributes = {};
21
- function create_telemetry_options_isTelemetryEnabled(options) {
22
- if (options) return options.telemetry?.enabled === true;
23
- return cachedConfig?.enabled === true;
24
- }
25
- const create_telemetry_options_getTracer = (options)=>{
26
- if (!create_telemetry_options_isTelemetryEnabled(options)) return api_trace.getTracer('c15t-noop');
27
- const tracer = options?.telemetry?.tracer ?? cachedConfig?.tracer;
28
- if (tracer) return tracer;
29
- return api_trace.getTracer(options?.appName ?? 'c15t');
30
- };
31
- const getMeter = (options)=>{
32
- if (!create_telemetry_options_isTelemetryEnabled(options)) return api_metrics.getMeter('c15t-noop');
33
- const meter = options?.telemetry?.meter ?? cachedConfig?.meter;
34
- if (meter) return meter;
35
- return api_metrics.getMeter(options?.appName ?? 'c15t');
36
- };
37
- function getDefaultAttributes() {
38
- return cachedDefaultAttributes;
39
- }
40
- const handleSpanError = (span, error)=>{
41
- span.setStatus({
42
- code: api_SpanStatusCode.ERROR,
43
- message: extractErrorMessage(error)
44
- });
45
- if (error instanceof Error) span.setAttribute('error.type', error.name);
46
- };
47
- const withSpanContext = async (span, operation)=>context["with"](api_trace.setSpan(context.active(), span), operation);
48
- function sanitizeAttributes(attrs) {
49
- return Object.fromEntries(Object.entries(attrs).filter(([_, v])=>null != v));
50
- }
51
- function createMetrics(meter) {
52
- const consentCreated = meter.createCounter('c15t.consent.created', {
53
- description: 'Number of consent submissions',
54
- unit: '1'
55
- });
56
- const consentAccepted = meter.createCounter('c15t.consent.accepted', {
57
- description: 'Number of consents accepted',
58
- unit: '1'
59
- });
60
- const consentRejected = meter.createCounter('c15t.consent.rejected', {
61
- description: 'Number of consents rejected',
62
- unit: '1'
63
- });
64
- const subjectCreated = meter.createCounter('c15t.subject.created', {
65
- description: 'Number of new subjects created',
66
- unit: '1'
67
- });
68
- const subjectLinked = meter.createCounter('c15t.subject.linked', {
69
- description: 'Number of subjects linked to external ID',
70
- unit: '1'
71
- });
72
- const consentCheckCount = meter.createCounter('c15t.consent_check.count', {
73
- description: 'Number of cross-device consent checks',
74
- unit: '1'
75
- });
76
- const initCount = meter.createCounter('c15t.init.count', {
77
- description: 'Number of init endpoint calls',
78
- unit: '1'
79
- });
80
- const httpRequestDuration = meter.createHistogram('c15t.http.request.duration', {
81
- description: 'HTTP request latency',
82
- unit: 'ms'
83
- });
84
- const httpRequestCount = meter.createCounter('c15t.http.request.count', {
85
- description: 'Number of HTTP requests',
86
- unit: '1'
87
- });
88
- const httpErrorCount = meter.createCounter('c15t.http.error.count', {
89
- description: 'Number of HTTP errors',
90
- unit: '1'
91
- });
92
- const dbQueryDuration = meter.createHistogram('c15t.db.query.duration', {
93
- description: 'Database query latency',
94
- unit: 'ms'
95
- });
96
- const dbQueryCount = meter.createCounter('c15t.db.query.count', {
97
- description: 'Number of database queries',
98
- unit: '1'
99
- });
100
- const dbErrorCount = meter.createCounter('c15t.db.error.count', {
101
- description: 'Number of database errors',
102
- unit: '1'
103
- });
104
- const cacheHit = meter.createCounter('c15t.cache.hit', {
105
- description: 'Number of cache hits',
106
- unit: '1'
107
- });
108
- const cacheMiss = meter.createCounter('c15t.cache.miss', {
109
- description: 'Number of cache misses',
110
- unit: '1'
111
- });
112
- const cacheLatency = meter.createHistogram('c15t.cache.latency', {
113
- description: 'Cache operation latency',
114
- unit: 'ms'
115
- });
116
- const gvlFetchDuration = meter.createHistogram('c15t.gvl.fetch.duration', {
117
- description: 'GVL fetch latency',
118
- unit: 'ms'
119
- });
120
- const gvlFetchCount = meter.createCounter('c15t.gvl.fetch.count', {
121
- description: 'Number of GVL fetches',
122
- unit: '1'
123
- });
124
- const gvlFetchError = meter.createCounter('c15t.gvl.fetch.error', {
125
- description: 'Number of GVL fetch errors',
126
- unit: '1'
127
- });
128
- return {
129
- consentCreated,
130
- consentAccepted,
131
- consentRejected,
132
- subjectCreated,
133
- subjectLinked,
134
- consentCheckCount,
135
- initCount,
136
- httpRequestDuration,
137
- httpRequestCount,
138
- httpErrorCount,
139
- dbQueryDuration,
140
- dbQueryCount,
141
- dbErrorCount,
142
- cacheHit,
143
- cacheMiss,
144
- cacheLatency,
145
- gvlFetchDuration,
146
- gvlFetchCount,
147
- gvlFetchError,
148
- recordConsentCreated (attributes) {
149
- consentCreated.add(1, sanitizeAttributes(attributes));
150
- },
151
- recordConsentAccepted (attributes) {
152
- consentAccepted.add(1, sanitizeAttributes(attributes));
153
- },
154
- recordConsentRejected (attributes) {
155
- consentRejected.add(1, sanitizeAttributes(attributes));
156
- },
157
- recordSubjectCreated (attributes) {
158
- subjectCreated.add(1, sanitizeAttributes(attributes));
159
- },
160
- recordSubjectLinked (identityProvider) {
161
- subjectLinked.add(1, {
162
- identityProvider: identityProvider || 'unknown'
163
- });
164
- },
165
- recordConsentCheck (type, found) {
166
- consentCheckCount.add(1, {
167
- type,
168
- found: String(found)
169
- });
170
- },
171
- recordInit (attributes) {
172
- initCount.add(1, sanitizeAttributes(attributes));
173
- },
174
- recordHttpRequest (attributes, durationMs) {
175
- const attrs = sanitizeAttributes(attributes);
176
- httpRequestCount.add(1, attrs);
177
- httpRequestDuration.record(durationMs, attrs);
178
- if (attributes.status >= 400) httpErrorCount.add(1, attrs);
179
- },
180
- recordDbQuery (attributes, durationMs) {
181
- const attrs = sanitizeAttributes(attributes);
182
- dbQueryCount.add(1, attrs);
183
- dbQueryDuration.record(durationMs, attrs);
184
- },
185
- recordDbError (attributes) {
186
- dbErrorCount.add(1, sanitizeAttributes(attributes));
187
- },
188
- recordCacheHit (layer) {
189
- cacheHit.add(1, {
190
- layer
191
- });
192
- },
193
- recordCacheMiss (layer) {
194
- cacheMiss.add(1, {
195
- layer
196
- });
197
- },
198
- recordCacheLatency (attributes, durationMs) {
199
- cacheLatency.record(durationMs, sanitizeAttributes(attributes));
200
- },
201
- recordGvlFetch (attributes, durationMs) {
202
- const attrs = sanitizeAttributes(attributes);
203
- gvlFetchCount.add(1, attrs);
204
- gvlFetchDuration.record(durationMs, attrs);
205
- },
206
- recordGvlError (attributes) {
207
- gvlFetchError.add(1, sanitizeAttributes(attributes));
208
- }
209
- };
210
- }
211
- let metricsInstance = null;
212
- function getMetrics(options) {
213
- if (metricsInstance) return metricsInstance;
214
- if (!create_telemetry_options_isTelemetryEnabled(options)) return null;
215
- metricsInstance = createMetrics(getMeter(options));
216
- return metricsInstance;
217
- }
218
- function parsePurposeIds(purposeIds) {
219
- if (null == purposeIds) return [];
220
- const ids = 'object' == typeof purposeIds && 'json' in purposeIds ? purposeIds.json : purposeIds;
221
- return Array.isArray(ids) ? ids : [];
222
- }
223
- async function batchLoadPolicies(policyIds, ctx) {
224
- const { db, registry } = ctx;
225
- const policyMap = new Map();
226
- if (policyIds.size > 0) {
227
- const policies = await db.findMany('consentPolicy', {
228
- where: (b)=>b('id', 'in', [
229
- ...policyIds
230
- ])
231
- });
232
- for (const p of policies)policyMap.set(p.id, p);
233
- }
234
- const uniqueTypes = new Set();
235
- for (const p of policyMap.values())uniqueTypes.add(p.type);
236
- const latestPolicyByType = new Map();
237
- for (const type of uniqueTypes){
238
- const latest = await registry.findOrCreatePolicy(type);
239
- if (latest) latestPolicyByType.set(type, latest.id);
240
- }
241
- return {
242
- policyMap,
243
- latestPolicyByType
244
- };
245
- }
246
- async function enrichConsents(consents, ctx) {
247
- if (0 === consents.length) return [];
248
- const policyIds = new Set();
249
- for (const c of consents)if (c.policyId) policyIds.add(c.policyId);
250
- const { policyMap, latestPolicyByType } = await batchLoadPolicies(policyIds, ctx);
251
- const allPurposeIds = new Set();
252
- for (const c of consents)for (const id of parsePurposeIds(c.purposeIds))allPurposeIds.add(id);
253
- const purposeMap = new Map();
254
- if (allPurposeIds.size > 0) {
255
- const purposes = await ctx.db.findMany('consentPurpose', {
256
- where: (b)=>b('id', 'in', [
257
- ...allPurposeIds
258
- ])
259
- });
260
- for (const p of purposes)purposeMap.set(p.id, p.code);
261
- }
262
- return consents.map((consent)=>{
263
- let policyType = 'unknown';
264
- let isLatestPolicy = false;
265
- if (consent.policyId) {
266
- const policy = policyMap.get(consent.policyId);
267
- if (policy) {
268
- policyType = policy.type;
269
- isLatestPolicy = latestPolicyByType.get(policyType) === consent.policyId;
270
- }
271
- }
272
- let preferences;
273
- const ids = parsePurposeIds(consent.purposeIds);
274
- if (ids.length > 0) {
275
- preferences = {};
276
- for (const purposeId of ids){
277
- const code = purposeMap.get(purposeId);
278
- if (code) preferences[code] = true;
279
- }
280
- }
281
- return {
282
- id: consent.id,
283
- type: policyType,
284
- policyId: consent.policyId ?? void 0,
285
- isLatestPolicy,
286
- preferences,
287
- givenAt: consent.givenAt
288
- };
289
- });
290
- }
291
- async function resolveConsentPolicies(consents, ctx) {
292
- if (0 === consents.length) return [];
293
- const policyIds = new Set();
294
- for (const c of consents)if (c.policyId) policyIds.add(c.policyId);
295
- const { policyMap, latestPolicyByType } = await batchLoadPolicies(policyIds, ctx);
296
- return consents.map((consent)=>{
297
- let policyType = 'unknown';
298
- let isLatestPolicy = false;
299
- if (consent.policyId) {
300
- const policy = policyMap.get(consent.policyId);
301
- if (policy) {
302
- policyType = policy.type;
303
- isLatestPolicy = latestPolicyByType.get(policyType) === consent.policyId;
304
- }
305
- }
306
- return {
307
- consentId: consent.id,
308
- policyType,
309
- policyId: consent.policyId ?? void 0,
310
- isLatestPolicy
311
- };
312
- });
313
- }
314
- const checkConsentHandler = async (c)=>{
315
- const ctx = c.get('c15tContext');
316
- const logger = ctx.logger;
317
- logger.info('Handling GET /consents/check request');
318
- const { db, registry } = ctx;
319
- const externalId = c.req.query('externalId');
320
- const type = c.req.query('type');
321
- if (!externalId) throw new HTTPException(422, {
322
- message: 'externalId query parameter is required',
323
- cause: {
324
- code: 'EXTERNAL_ID_REQUIRED'
325
- }
326
- });
327
- if (!type) throw new HTTPException(422, {
328
- message: 'type query parameter is required',
329
- cause: {
330
- code: 'TYPE_REQUIRED'
331
- }
332
- });
333
- const types = type.split(',').map((t)=>t.trim());
334
- logger.debug('Request parameters', {
335
- externalId,
336
- types
337
- });
338
- try {
339
- const subjects = await db.findMany('subject', {
340
- where: (b)=>b('externalId', '=', externalId)
341
- });
342
- const subjectIds = subjects.map((s)=>s.id);
343
- const results = {};
344
- for (const t of types)results[t] = {
345
- hasConsent: false,
346
- isLatestPolicy: false
347
- };
348
- if (0 === subjectIds.length) {
349
- logger.debug('No subjects found for externalId', {
350
- externalId
351
- });
352
- return c.json({
353
- results
354
- });
355
- }
356
- const allConsents = await Promise.all(subjectIds.map((subjectId)=>db.findMany('consent', {
357
- where: (b)=>b('subjectId', '=', subjectId)
358
- })));
359
- const consents = allConsents.flat();
360
- const policyInfos = await resolveConsentPolicies(consents, {
361
- db,
362
- registry
363
- });
364
- for (const info of policyInfos){
365
- if (!types.includes(info.policyType)) continue;
366
- const entry = results[info.policyType];
367
- if (entry) {
368
- entry.hasConsent = true;
369
- if (info.isLatestPolicy) entry.isLatestPolicy = true;
370
- }
371
- }
372
- logger.debug('Consent check results', {
373
- externalId,
374
- results
375
- });
376
- const metrics = getMetrics();
377
- if (metrics) for (const [type, result] of Object.entries(results))metrics.recordConsentCheck(type, result.hasConsent);
378
- return c.json({
379
- results
380
- });
381
- } catch (error) {
382
- logger.error('Error in GET /consents/check handler', {
383
- error: extractErrorMessage(error),
384
- errorType: error instanceof Error ? error.constructor.name : typeof error
385
- });
386
- if (error instanceof HTTPException) throw error;
387
- throw new HTTPException(500, {
388
- message: 'Internal server error',
389
- cause: {
390
- code: 'INTERNAL_SERVER_ERROR'
391
- }
392
- });
393
- }
394
- };
395
- const createConsentRoutes = ()=>{
396
- const app = new Hono();
397
- app.get('/check', describeRoute({
398
- summary: 'Check consent by external user ID',
399
- description: `Pre-banner cross-device consent check. Use to avoid showing the banner when the user has already consented on another device.
400
-
401
- **Query parameters:**
402
- - \`externalId\` – External user ID to check
403
- - \`type\` – Consent type(s) to check (comma-separated)`,
404
- tags: [
405
- 'Consent'
406
- ],
407
- responses: {
408
- 200: {
409
- description: 'Consent check result per requested type(s)',
410
- content: {
411
- 'application/json': {
412
- schema: resolver(checkConsentOutputSchema)
413
- }
414
- }
415
- },
416
- 422: {
417
- description: 'Invalid or missing query parameters'
418
- }
419
- }
420
- }), validator('query', checkConsentQuerySchema), checkConsentHandler);
421
- return app;
422
- };
423
- async function executeWithSpan(span, operation) {
424
- try {
425
- const result = await withSpanContext(span, operation);
426
- span.setStatus({
427
- code: api_SpanStatusCode.OK
428
- });
429
- return result;
430
- } catch (error) {
431
- handleSpanError(span, error);
432
- throw error;
433
- } finally{
434
- span.end();
435
- }
436
- }
437
- function resolveDefaultAttributes(options) {
438
- return options?.telemetry?.defaultAttributes || getDefaultAttributes();
439
- }
440
- async function withExternalSpan(attributes, operation, options) {
441
- if (!create_telemetry_options_isTelemetryEnabled(options)) return operation();
442
- const tracer = create_telemetry_options_getTracer(options);
443
- const url = new URL(attributes.url);
444
- const spanName = `HTTP ${attributes.method} ${url.hostname}`;
445
- const span = tracer.startSpan(spanName, {
446
- kind: api_SpanKind.CLIENT,
447
- attributes: {
448
- 'http.method': attributes.method,
449
- 'http.url': `${url.origin}${url.pathname}`,
450
- 'http.host': url.hostname,
451
- ...resolveDefaultAttributes(options),
452
- ...Object.fromEntries(Object.entries(attributes).filter(([key])=>![
453
- 'url',
454
- 'method'
455
- ].includes(key)))
456
- }
457
- });
458
- return executeWithSpan(span, operation);
459
- }
460
- async function withCacheSpan(operation, layer, fn, options) {
461
- if (!create_telemetry_options_isTelemetryEnabled(options)) return fn();
462
- const tracer = create_telemetry_options_getTracer(options);
463
- const spanName = `cache.${layer}.${operation}`;
464
- const span = tracer.startSpan(spanName, {
465
- kind: api_SpanKind.CLIENT,
466
- attributes: {
467
- 'cache.operation': operation,
468
- 'cache.layer': layer,
469
- ...resolveDefaultAttributes(options)
470
- }
471
- });
472
- return executeWithSpan(span, fn);
473
- }
474
- const GVL_TTL_MS = 259200000;
475
- const memory_memoryCache = new Map();
476
- function createMemoryCacheAdapter() {
477
- return {
478
- async get (key) {
479
- const entry = memory_memoryCache.get(key);
480
- if (!entry) return null;
481
- if (Date.now() > entry.expiresAt) {
482
- memory_memoryCache.delete(key);
483
- return null;
484
- }
485
- return entry.value;
486
- },
487
- async set (key, value, ttlMs = 300000) {
488
- memory_memoryCache.set(key, {
489
- value,
490
- expiresAt: Date.now() + ttlMs
491
- });
492
- },
493
- async delete (key) {
494
- memory_memoryCache.delete(key);
495
- },
496
- async has (key) {
497
- const entry = memory_memoryCache.get(key);
498
- if (!entry) return false;
499
- if (Date.now() > entry.expiresAt) {
500
- memory_memoryCache.delete(key);
501
- return false;
502
- }
503
- return true;
504
- }
505
- };
506
- }
507
- function createGVLCacheKey(appName, language, vendorIds) {
508
- const sortedIds = vendorIds ? [
509
- ...vendorIds
510
- ].sort((a, b)=>a - b).join(',') : 'all';
511
- return `${appName}:gvl:${language}:${sortedIds}`;
512
- }
513
- const GVL_ENDPOINT = 'https://gvl.consent.io';
514
- const inflightRequests = new Map();
515
- async function fetchGVLWithLanguage(language, vendorIds, endpoint = GVL_ENDPOINT) {
516
- const sortedVendorIds = vendorIds ? [
517
- ...vendorIds
518
- ].sort((a, b)=>a - b) : [];
519
- const dedupeKey = `${endpoint}|${language}|${sortedVendorIds.join(',')}`;
520
- const existingRequest = inflightRequests.get(dedupeKey);
521
- if (existingRequest) return existingRequest;
522
- const url = new URL(endpoint);
523
- if (sortedVendorIds.length > 0) url.searchParams.set('vendorIds', sortedVendorIds.join(','));
524
- const promise = (async ()=>{
525
- const fetchStart = Date.now();
526
- try {
527
- const gvl = await withExternalSpan({
528
- url: url.toString(),
529
- method: 'GET'
530
- }, async ()=>{
531
- const response = await fetch(url.toString(), {
532
- headers: {
533
- 'Accept-Language': language
534
- }
535
- });
536
- if (204 === response.status) return null;
537
- if (!response.ok) throw new Error(`Failed to fetch GVL: ${response.status} ${response.statusText}`);
538
- const text = await response.text();
539
- const trimmed = text.trim().replace(/^\uFEFF/, '');
540
- let parsed;
541
- try {
542
- parsed = JSON.parse(trimmed);
543
- } catch {
544
- let depth = 0;
545
- let end = -1;
546
- const start = trimmed.indexOf('{');
547
- if (start >= 0) for(let i = start; i < trimmed.length; i++){
548
- const c = trimmed[i];
549
- if ('{' === c) depth++;
550
- else if ('}' === c) {
551
- depth--;
552
- if (0 === depth) {
553
- end = i + 1;
554
- break;
555
- }
556
- }
557
- }
558
- if (end > 0) parsed = JSON.parse(trimmed.slice(0, end));
559
- else throw new SyntaxError('Invalid GVL response: not valid JSON');
560
- }
561
- if (!parsed.vendorListVersion || !parsed.purposes || !parsed.vendors) throw new Error('Invalid GVL response: missing required fields');
562
- return parsed;
563
- });
564
- getMetrics()?.recordGvlFetch({
565
- language,
566
- source: 'fetch',
567
- status: 200
568
- }, Date.now() - fetchStart);
569
- return gvl;
570
- } catch (error) {
571
- getMetrics()?.recordGvlError({
572
- language,
573
- errorType: error instanceof Error ? error.name : 'UnknownError'
574
- });
575
- throw error;
576
- } finally{
577
- inflightRequests.delete(dedupeKey);
578
- }
579
- })();
580
- inflightRequests.set(dedupeKey, promise);
581
- return promise;
582
- }
583
- function createGVLResolver(options) {
584
- const { appName, bundled, cacheAdapter, vendorIds, endpoint } = options;
585
- const memoryCache = createMemoryCacheAdapter();
586
- return {
587
- async get (language) {
588
- const cacheKey = createGVLCacheKey(appName, language, vendorIds);
589
- if (bundled?.[language]) return bundled[language];
590
- const memoryHit = await withCacheSpan('get', 'memory', ()=>memoryCache.get(cacheKey));
591
- if (memoryHit) {
592
- getMetrics()?.recordCacheHit('memory');
593
- return memoryHit;
594
- }
595
- getMetrics()?.recordCacheMiss('memory');
596
- if (cacheAdapter) {
597
- const externalHit = await withCacheSpan('get', 'external', ()=>cacheAdapter.get(cacheKey));
598
- if (externalHit) {
599
- getMetrics()?.recordCacheHit('external');
600
- await withCacheSpan('set', 'memory', ()=>memoryCache.set(cacheKey, externalHit, 300000));
601
- return externalHit;
602
- }
603
- getMetrics()?.recordCacheMiss('external');
604
- }
605
- const gvl = await fetchGVLWithLanguage(language, vendorIds, endpoint);
606
- if (gvl) {
607
- await withCacheSpan('set', 'memory', ()=>memoryCache.set(cacheKey, gvl, 300000));
608
- if (cacheAdapter) await withCacheSpan('set', 'external', ()=>cacheAdapter.set(cacheKey, gvl, GVL_TTL_MS));
609
- }
610
- return gvl;
611
- }
612
- };
613
- }
614
- function geo_normalizeHeader(value) {
615
- if (!value) return null;
616
- return Array.isArray(value) ? value[0] ?? null : value;
617
- }
618
- function getGeoHeaders(headers) {
619
- const countryCode = geo_normalizeHeader(headers.get('x-c15t-country')) ?? geo_normalizeHeader(headers.get('cf-ipcountry')) ?? geo_normalizeHeader(headers.get('x-vercel-ip-country')) ?? geo_normalizeHeader(headers.get('x-amz-cf-ipcountry')) ?? geo_normalizeHeader(headers.get('x-country-code'));
620
- const regionCode = geo_normalizeHeader(headers.get('x-c15t-region')) ?? geo_normalizeHeader(headers.get('x-vercel-ip-country-region')) ?? geo_normalizeHeader(headers.get('x-region-code'));
621
- return {
622
- countryCode,
623
- regionCode
624
- };
625
- }
626
- function checkJurisdiction(countryCode, regionCode) {
627
- const jurisdictions = {
628
- EU: new Set([
629
- 'AT',
630
- 'BE',
631
- 'BG',
632
- 'HR',
633
- 'CY',
634
- 'CZ',
635
- 'DK',
636
- 'EE',
637
- 'FI',
638
- 'FR',
639
- 'DE',
640
- 'GR',
641
- 'HU',
642
- 'IE',
643
- 'IT',
644
- 'LV',
645
- 'LT',
646
- 'LU',
647
- 'MT',
648
- 'NL',
649
- 'PL',
650
- 'PT',
651
- 'RO',
652
- 'SK',
653
- 'SI',
654
- 'ES',
655
- 'SE'
656
- ]),
657
- EEA: new Set([
658
- 'IS',
659
- 'NO',
660
- 'LI'
661
- ]),
662
- UK: new Set([
663
- 'GB'
664
- ]),
665
- CH: new Set([
666
- 'CH'
667
- ]),
668
- BR: new Set([
669
- 'BR'
670
- ]),
671
- CA: new Set([
672
- 'CA'
673
- ]),
674
- AU: new Set([
675
- 'AU'
676
- ]),
677
- JP: new Set([
678
- 'JP'
679
- ]),
680
- KR: new Set([
681
- 'KR'
682
- ]),
683
- US_CCPA_REGIONS: new Set([
684
- 'CA'
685
- ]),
686
- CA_QC_REGIONS: new Set([
687
- 'QC'
688
- ])
689
- };
690
- let jurisdiction = 'NONE';
691
- if (countryCode) {
692
- const normalizedCountryCode = countryCode.toUpperCase();
693
- const normalizedRegionCode = regionCode && 'string' == typeof regionCode ? (regionCode.includes('-') ? regionCode.split('-').pop() : regionCode).toUpperCase() : null;
694
- if ('US' === normalizedCountryCode && normalizedRegionCode && jurisdictions.US_CCPA_REGIONS.has(normalizedRegionCode)) return 'CCPA';
695
- if ('CA' === normalizedCountryCode && normalizedRegionCode && jurisdictions.CA_QC_REGIONS.has(normalizedRegionCode)) return 'QC_LAW25';
696
- const jurisdictionMap = [
697
- {
698
- sets: [
699
- jurisdictions.UK
700
- ],
701
- code: 'UK_GDPR'
702
- },
703
- {
704
- sets: [
705
- jurisdictions.EU,
706
- jurisdictions.EEA
707
- ],
708
- code: 'GDPR'
709
- },
710
- {
711
- sets: [
712
- jurisdictions.CH
713
- ],
714
- code: 'CH'
715
- },
716
- {
717
- sets: [
718
- jurisdictions.BR
719
- ],
720
- code: 'BR'
721
- },
722
- {
723
- sets: [
724
- jurisdictions.CA
725
- ],
726
- code: 'PIPEDA'
727
- },
728
- {
729
- sets: [
730
- jurisdictions.AU
731
- ],
732
- code: 'AU'
733
- },
734
- {
735
- sets: [
736
- jurisdictions.JP
737
- ],
738
- code: 'APPI'
739
- },
740
- {
741
- sets: [
742
- jurisdictions.KR
743
- ],
744
- code: 'PIPA'
745
- }
746
- ];
747
- for (const { sets, code } of jurisdictionMap)if (sets.some((set)=>set.has(normalizedCountryCode))) {
748
- jurisdiction = code;
749
- break;
750
- }
751
- }
752
- return jurisdiction;
753
- }
754
- async function getLocation(request, options) {
755
- if (options.disableGeoLocation) return {
756
- countryCode: null,
757
- regionCode: null
758
- };
759
- const { countryCode, regionCode } = getGeoHeaders(request.headers);
760
- return {
761
- countryCode,
762
- regionCode
763
- };
764
- }
765
- function getJurisdiction(location, options) {
766
- if (options.disableGeoLocation) return 'GDPR';
767
- return checkJurisdiction(location.countryCode, location.regionCode);
768
- }
769
- function isSupportedBaseLanguage(lang) {
770
- return lang in baseTranslations;
771
- }
772
- function translations_getTranslationsData(acceptLanguage, customTranslations) {
773
- const supportedDefaultLanguages = Object.keys(baseTranslations);
774
- const supportedCustomLanguages = Object.keys(customTranslations || {});
775
- const supportedLanguages = [
776
- ...supportedDefaultLanguages,
777
- ...supportedCustomLanguages
778
- ];
779
- const preferredLanguage = selectLanguage(supportedLanguages, {
780
- header: acceptLanguage,
781
- fallback: 'en'
782
- });
783
- const base = isSupportedBaseLanguage(preferredLanguage) ? baseTranslations[preferredLanguage] : baseTranslations.en;
784
- const custom = supportedCustomLanguages.includes(preferredLanguage) ? customTranslations?.[preferredLanguage] : {};
785
- const translations = custom ? deepMergeTranslations(base, custom) : base;
786
- return {
787
- translations: translations,
788
- language: preferredLanguage
789
- };
790
- }
791
- const createInitRoute = (options)=>{
792
- const app = new Hono();
793
- app.get('/', describeRoute({
794
- summary: 'Get initial consent manager state',
795
- description: `Returns the initial state required to render the consent manager.
796
-
797
- - **Jurisdiction** – User's jurisdiction (defaults to GDPR if geo-location is disabled)
798
- - **Location** – User's location (null if geo-location is disabled)
799
- - **Translations** – Consent manager copy (from \`Accept-Language\` header)
800
- - **Branding** – Configured branding key
801
- - **GVL** – Global Vendor List when enabled
802
-
803
- Use for geo-targeted consent banners and regional compliance.`,
804
- tags: [
805
- 'Init'
806
- ],
807
- responses: {
808
- 200: {
809
- description: 'Initialization payload (jurisdiction, location, translations, branding, GVL)',
810
- content: {
811
- 'application/json': {
812
- schema: resolver(initOutputSchema)
813
- }
814
- }
815
- }
816
- }
817
- }), async (c)=>{
818
- const request = c.req.raw;
819
- const acceptLanguage = request.headers.get('accept-language') || 'en';
820
- const location = await getLocation(request, options);
821
- const jurisdiction = getJurisdiction(location, options);
822
- const translationsResult = translations_getTranslationsData(acceptLanguage, options.customTranslations);
823
- let gvl = null;
824
- if (options.iab?.enabled) {
825
- const language = translationsResult.language.split('-')[0] || 'en';
826
- const gvlResolver = createGVLResolver({
827
- appName: options.appName || 'c15t',
828
- bundled: options.iab.bundled,
829
- cacheAdapter: options.cache?.adapter,
830
- vendorIds: options.iab.vendorIds,
831
- endpoint: options.iab.endpoint
832
- });
833
- gvl = await gvlResolver.get(language);
834
- }
835
- const customVendors = options.iab?.customVendors;
836
- const gpc = '1' === request.headers.get('sec-gpc');
837
- getMetrics()?.recordInit({
838
- jurisdiction,
839
- country: location?.countryCode ?? void 0,
840
- region: location?.regionCode ?? void 0,
841
- gpc
842
- });
843
- return c.json({
844
- jurisdiction,
845
- location,
846
- translations: translationsResult,
847
- branding: options.branding || 'c15t',
848
- gvl,
849
- customVendors,
850
- ...options.iab?.cmpId != null && {
851
- cmpId: options.iab.cmpId
852
- }
853
- });
854
- });
855
- return app;
856
- };
857
- function getHeaders(headers) {
858
- if (!headers) return {
859
- countryCode: null,
860
- regionCode: null,
861
- acceptLanguage: null
862
- };
863
- const normalizeHeader = (value)=>{
864
- if (!value) return null;
865
- return Array.isArray(value) ? value[0] ?? null : value;
866
- };
867
- const countryCode = normalizeHeader(headers.get('x-c15t-country')) ?? normalizeHeader(headers.get('cf-ipcountry')) ?? normalizeHeader(headers.get('x-vercel-ip-country')) ?? normalizeHeader(headers.get('x-amz-cf-ipcountry')) ?? normalizeHeader(headers.get('x-country-code'));
868
- const regionCode = normalizeHeader(headers.get('x-c15t-region')) ?? normalizeHeader(headers.get('x-vercel-ip-country-region')) ?? normalizeHeader(headers.get('x-region-code'));
869
- const acceptLanguage = normalizeHeader(headers.get('accept-language'));
870
- return {
871
- countryCode,
872
- regionCode,
873
- acceptLanguage
874
- };
875
- }
876
- const statusHandler = async (c)=>{
877
- const ctx = c.get('c15tContext');
878
- const { countryCode, regionCode, acceptLanguage } = getHeaders(ctx.headers);
879
- const clientInfo = {
880
- ip: ctx.ipAddress ?? null,
881
- acceptLanguage,
882
- userAgent: ctx.userAgent ?? null,
883
- region: {
884
- countryCode,
885
- regionCode
886
- }
887
- };
888
- try {
889
- await ctx.db.findFirst('subject', {});
890
- return c.json({
891
- version: version_version,
892
- timestamp: new Date(),
893
- client: clientInfo
894
- });
895
- } catch (error) {
896
- ctx.logger.error('Database health check failed', {
897
- error
898
- });
899
- throw new HTTPException(503, {
900
- message: 'Database health check failed',
901
- cause: {
902
- code: 'SERVICE_UNAVAILABLE',
903
- error
904
- }
905
- });
906
- }
907
- };
908
- const createStatusRoute = ()=>{
909
- const app = new Hono();
910
- app.get('/', describeRoute({
911
- summary: 'Health check and API status',
912
- description: `Returns API version, timestamp, and client info (IP, region, user agent).
913
-
914
- Use for health checks, load balancer probes, and debugging. Performs a lightweight DB check; returns 503 if the database is unreachable.`,
915
- tags: [
916
- 'Status'
917
- ],
918
- responses: {
919
- 200: {
920
- description: 'API is healthy (version, timestamp, client info)',
921
- content: {
922
- 'application/json': {
923
- schema: resolver(statusOutputSchema)
924
- }
925
- }
926
- },
927
- 503: {
928
- description: 'Service unavailable (e.g. database unreachable)'
929
- }
930
- }
931
- }), statusHandler);
932
- return app;
933
- };
934
- const getSubjectHandler = async (c)=>{
935
- const ctx = c.get('c15tContext');
936
- const logger = ctx.logger;
937
- logger.info('Handling GET /subjects/:id request');
938
- const { db, registry } = ctx;
939
- const subjectId = c.req.param('id');
940
- const type = c.req.query('type');
941
- const typeFilter = type?.split(',').map((t)=>t.trim()) || [];
942
- logger.debug('Request parameters', {
943
- subjectId,
944
- typeFilter
945
- });
946
- try {
947
- const subject = await db.findFirst('subject', {
948
- where: (b)=>b('id', '=', subjectId)
949
- });
950
- if (!subject) throw new HTTPException(404, {
951
- message: 'Subject not found',
952
- cause: {
953
- code: 'SUBJECT_NOT_FOUND',
954
- subjectId
955
- }
956
- });
957
- const consents = await db.findMany('consent', {
958
- where: (b)=>b('subjectId', '=', subjectId)
959
- });
960
- const consentItems = await enrichConsents(consents, {
961
- db,
962
- registry
963
- });
964
- const filteredConsents = typeFilter.length > 0 ? consentItems.filter((consent)=>typeFilter.includes(consent.type)) : consentItems;
965
- const isValid = 0 === typeFilter.length || typeFilter.every((t)=>filteredConsents.some((consent)=>consent.type === t && consent.isLatestPolicy));
966
- return c.json({
967
- subject: {
968
- id: subject.id,
969
- externalId: subject.externalId ?? void 0,
970
- createdAt: subject.createdAt
971
- },
972
- consents: filteredConsents,
973
- isValid
974
- });
975
- } catch (error) {
976
- logger.error('Error in GET /subjects/:id handler', {
977
- error: extractErrorMessage(error),
978
- errorType: error instanceof Error ? error.constructor.name : typeof error
979
- });
980
- if (error instanceof HTTPException) throw error;
981
- throw new HTTPException(500, {
982
- message: 'Internal server error',
983
- cause: {
984
- code: 'INTERNAL_SERVER_ERROR'
985
- }
986
- });
987
- }
988
- };
989
- const listSubjectsHandler = async (c)=>{
990
- const ctx = c.get('c15tContext');
991
- const logger = ctx.logger;
992
- logger.info('Handling GET /subjects request');
993
- const { db, registry } = ctx;
994
- if (!ctx.apiKeyAuthenticated) throw new HTTPException(401, {
995
- message: 'API key required. Use Authorization: Bearer <api_key>',
996
- cause: {
997
- code: 'UNAUTHORIZED'
998
- }
999
- });
1000
- const externalId = c.req.query('externalId');
1001
- if (!externalId) throw new HTTPException(422, {
1002
- message: 'externalId query parameter is required',
1003
- cause: {
1004
- code: 'EXTERNAL_ID_REQUIRED'
1005
- }
1006
- });
1007
- logger.debug('Request parameters', {
1008
- externalId
1009
- });
1010
- try {
1011
- const subjects = await db.findMany('subject', {
1012
- where: (b)=>b('externalId', '=', externalId)
1013
- });
1014
- const subjectItems = await Promise.all(subjects.map(async (subject)=>{
1015
- const consents = await db.findMany('consent', {
1016
- where: (b)=>b('subjectId', '=', subject.id)
1017
- });
1018
- const consentItems = await enrichConsents(consents, {
1019
- db,
1020
- registry
1021
- });
1022
- return {
1023
- id: subject.id,
1024
- externalId: subject.externalId ?? externalId,
1025
- createdAt: subject.createdAt,
1026
- consents: consentItems
1027
- };
1028
- }));
1029
- logger.info('Found subjects for externalId', {
1030
- externalId,
1031
- count: subjectItems.length
1032
- });
1033
- return c.json({
1034
- subjects: subjectItems
1035
- });
1036
- } catch (error) {
1037
- logger.error('Error in GET /subjects handler', {
1038
- error: extractErrorMessage(error),
1039
- errorType: error instanceof Error ? error.constructor.name : typeof error
1040
- });
1041
- if (error instanceof HTTPException) throw error;
1042
- throw new HTTPException(500, {
1043
- message: 'Internal server error',
1044
- cause: {
1045
- code: 'INTERNAL_SERVER_ERROR'
1046
- }
1047
- });
1048
- }
1049
- };
1050
- const prefixes = {
1051
- auditLog: 'log',
1052
- consent: 'cns',
1053
- consentPolicy: 'pol',
1054
- consentPurpose: 'pur',
1055
- domain: 'dom',
1056
- subject: 'sub'
1057
- };
1058
- const b58 = base_x('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
1059
- function generateId(model) {
1060
- const buf = crypto.getRandomValues(new Uint8Array(20));
1061
- const prefix = prefixes[model];
1062
- const EPOCH_TIMESTAMP = 1700000000000;
1063
- const t = Date.now() - EPOCH_TIMESTAMP;
1064
- const high = Math.floor(t / 0x100000000);
1065
- const low = t >>> 0;
1066
- buf[0] = high >>> 24 & 255;
1067
- buf[1] = high >>> 16 & 255;
1068
- buf[2] = high >>> 8 & 255;
1069
- buf[3] = 255 & high;
1070
- buf[4] = low >>> 24 & 255;
1071
- buf[5] = low >>> 16 & 255;
1072
- buf[6] = low >>> 8 & 255;
1073
- buf[7] = 255 & low;
1074
- return `${prefix}_${b58.encode(buf)}`;
1075
- }
1076
- async function generateUniqueId(db, model, ctx, options = {}) {
1077
- const { maxRetries = 10, attempt = 0, baseDelay = 5 } = options;
1078
- if (attempt >= maxRetries) {
1079
- const error = new Error(`Failed to generate unique ID for ${model} after ${maxRetries} attempts`);
1080
- ctx?.logger?.error?.('ID generation failed', {
1081
- model,
1082
- maxRetries
1083
- });
1084
- throw error;
1085
- }
1086
- const id = generateId(model);
1087
- try {
1088
- const existing = await db.findFirst(model, {
1089
- where: (b)=>b('id', '=', id)
1090
- });
1091
- if (existing) {
1092
- ctx?.logger?.debug?.('ID conflict detected', {
1093
- id,
1094
- model,
1095
- attempt: attempt + 1,
1096
- maxRetries
1097
- });
1098
- const delay = Math.min(baseDelay * 2 ** attempt, 1000);
1099
- await new Promise((resolve)=>setTimeout(resolve, delay));
1100
- return generateUniqueId(db, model, ctx, {
1101
- maxRetries,
1102
- attempt: attempt + 1,
1103
- baseDelay
1104
- });
1105
- }
1106
- return id;
1107
- } catch (error) {
1108
- ctx?.logger?.error?.('Error checking ID uniqueness', {
1109
- error: error.message,
1110
- model,
1111
- attempt
1112
- });
1113
- if (attempt < maxRetries - 1) {
1114
- const delay = Math.min(baseDelay * 2 ** attempt, 2000);
1115
- await new Promise((resolve)=>setTimeout(resolve, delay));
1116
- return generateUniqueId(db, model, ctx, {
1117
- maxRetries,
1118
- attempt: attempt + 1,
1119
- baseDelay
1120
- });
1121
- }
1122
- throw error;
1123
- }
1124
- }
1125
- const patchSubjectHandler = async (c)=>{
1126
- const ctx = c.get('c15tContext');
1127
- const logger = ctx.logger;
1128
- logger.info('Handling PATCH /subjects/:id request');
1129
- const { db } = ctx;
1130
- const subjectId = c.req.param('id');
1131
- const body = await c.req.json();
1132
- const { externalId, identityProvider = 'external' } = body;
1133
- logger.debug('Request parameters', {
1134
- subjectId,
1135
- externalId,
1136
- identityProvider
1137
- });
1138
- try {
1139
- const subject = await db.findFirst('subject', {
1140
- where: (b)=>b('id', '=', subjectId)
1141
- });
1142
- if (!subject) throw new HTTPException(404, {
1143
- message: 'Subject not found',
1144
- cause: {
1145
- code: 'SUBJECT_NOT_FOUND',
1146
- subjectId
1147
- }
1148
- });
1149
- await db.transaction(async (tx)=>{
1150
- await tx.updateMany('subject', {
1151
- where: (b)=>b('id', '=', subjectId),
1152
- set: {
1153
- externalId,
1154
- identityProvider,
1155
- updatedAt: new Date()
1156
- }
1157
- });
1158
- await tx.create('auditLog', {
1159
- id: await generateUniqueId(tx, 'auditLog', ctx),
1160
- subjectId,
1161
- entityType: 'subject',
1162
- entityId: subjectId,
1163
- actionType: 'identify_user',
1164
- ipAddress: ctx.ipAddress || null,
1165
- userAgent: ctx.userAgent || null,
1166
- changes: {
1167
- externalId: {
1168
- from: subject.externalId,
1169
- to: externalId
1170
- },
1171
- identityProvider: {
1172
- from: subject.identityProvider,
1173
- to: identityProvider
1174
- }
1175
- },
1176
- metadata: {
1177
- externalId,
1178
- identityProvider
1179
- }
1180
- });
1181
- });
1182
- logger.info('Subject linked to external ID', {
1183
- subjectId,
1184
- externalId,
1185
- identityProvider
1186
- });
1187
- getMetrics()?.recordSubjectLinked(identityProvider);
1188
- return c.json({
1189
- success: true,
1190
- subject: {
1191
- id: subjectId,
1192
- externalId
1193
- }
1194
- });
1195
- } catch (error) {
1196
- logger.error('Error in PATCH /subjects/:id handler', {
1197
- error: extractErrorMessage(error),
1198
- errorType: error instanceof Error ? error.constructor.name : typeof error
1199
- });
1200
- if (error instanceof HTTPException) throw error;
1201
- throw new HTTPException(500, {
1202
- message: 'Internal server error',
1203
- cause: {
1204
- code: 'INTERNAL_SERVER_ERROR'
1205
- }
1206
- });
1207
- }
1208
- };
1209
- const postSubjectHandler = async (c)=>{
1210
- const ctx = c.get('c15tContext');
1211
- const logger = ctx.logger;
1212
- logger.info('Handling POST /subjects request');
1213
- const { db, registry } = ctx;
1214
- const input = await c.req.json();
1215
- const { type, subjectId, identityProvider, externalSubjectId, domain, metadata, givenAt: givenAtEpoch } = input;
1216
- const preferences = 'preferences' in input ? input.preferences : void 0;
1217
- const givenAt = new Date(givenAtEpoch);
1218
- const rawConsentAction = 'consentAction' in input ? input.consentAction : void 0;
1219
- let derivedConsentAction;
1220
- if ('all' === rawConsentAction) derivedConsentAction = 'accept_all';
1221
- else if ('necessary' === rawConsentAction) derivedConsentAction = 'opt-out' === input.jurisdictionModel ? 'opt_out' : 'reject_all';
1222
- else if ('custom' === rawConsentAction) derivedConsentAction = 'custom';
1223
- logger.debug('Request parameters', {
1224
- type,
1225
- subjectId,
1226
- identityProvider,
1227
- externalSubjectId,
1228
- domain
1229
- });
1230
- try {
1231
- const subject = await registry.findOrCreateSubject({
1232
- subjectId,
1233
- externalSubjectId,
1234
- identityProvider,
1235
- ipAddress: ctx.ipAddress
1236
- });
1237
- if (!subject) throw new HTTPException(500, {
1238
- message: 'Failed to create subject',
1239
- cause: {
1240
- code: 'SUBJECT_CREATION_FAILED',
1241
- subjectId
1242
- }
1243
- });
1244
- logger.debug('Subject found/created', {
1245
- subjectId: subject.id
1246
- });
1247
- const domainRecord = await registry.findOrCreateDomain(domain);
1248
- if (!domainRecord) throw new HTTPException(500, {
1249
- message: 'Failed to create domain',
1250
- cause: {
1251
- code: 'DOMAIN_CREATION_FAILED',
1252
- domain
1253
- }
1254
- });
1255
- let policyId;
1256
- let purposeIds = [];
1257
- const inputPolicyId = 'policyId' in input ? input.policyId : void 0;
1258
- if (inputPolicyId) {
1259
- policyId = inputPolicyId;
1260
- const policy = await registry.findConsentPolicyById(inputPolicyId);
1261
- if (!policy) throw new HTTPException(404, {
1262
- message: 'Policy not found',
1263
- cause: {
1264
- code: 'POLICY_NOT_FOUND',
1265
- policyId,
1266
- type
1267
- }
1268
- });
1269
- if (!policy.isActive) throw new HTTPException(400, {
1270
- message: 'Policy is inactive',
1271
- cause: {
1272
- code: 'POLICY_INACTIVE',
1273
- policyId,
1274
- type
1275
- }
1276
- });
1277
- } else {
1278
- const policy = await registry.findOrCreatePolicy(type);
1279
- if (!policy) throw new HTTPException(500, {
1280
- message: 'Failed to create policy',
1281
- cause: {
1282
- code: 'POLICY_CREATION_FAILED',
1283
- type
1284
- }
1285
- });
1286
- policyId = policy.id;
1287
- }
1288
- if (preferences) {
1289
- const consentedPurposes = Object.entries(preferences).filter(([_, isConsented])=>isConsented).map(([purposeCode])=>purposeCode);
1290
- logger.debug('Consented purposes', {
1291
- consentedPurposes
1292
- });
1293
- const purposesRaw = await Promise.all(consentedPurposes.map((purposeCode)=>registry.findOrCreateConsentPurposeByCode(purposeCode)));
1294
- const purposes = purposesRaw.map((purpose)=>purpose?.id ?? null).filter((id)=>Boolean(id));
1295
- logger.debug('Filtered purposes', {
1296
- purposes
1297
- });
1298
- if (0 === purposes.length) logger.warn('No valid purpose IDs found after filtering. Using empty list.', {
1299
- consentedPurposes
1300
- });
1301
- purposeIds = purposes;
1302
- }
1303
- const existingConsent = await db.findFirst('consent', {
1304
- where: (b)=>b.and(b('subjectId', '=', subject.id), b('domainId', '=', domainRecord.id), b('policyId', '=', policyId), b('givenAt', '=', givenAt))
1305
- });
1306
- if (existingConsent) {
1307
- logger.debug('Duplicate consent detected, returning existing record', {
1308
- consentId: existingConsent.id
1309
- });
1310
- return c.json({
1311
- subjectId: subject.id,
1312
- consentId: existingConsent.id,
1313
- domainId: domainRecord.id,
1314
- domain: domainRecord.name,
1315
- type,
1316
- metadata,
1317
- uiSource: input.uiSource,
1318
- givenAt: existingConsent.givenAt
1319
- });
1320
- }
1321
- const result = await db.transaction(async (tx)=>{
1322
- logger.debug('Creating consent record', {
1323
- subjectId: subject.id,
1324
- domainId: domainRecord.id,
1325
- policyId,
1326
- purposeIds
1327
- });
1328
- const consentRecord = await tx.create('consent', {
1329
- id: await generateUniqueId(tx, 'consent', ctx),
1330
- subjectId: subject.id,
1331
- domainId: domainRecord.id,
1332
- policyId,
1333
- purposeIds: {
1334
- json: purposeIds
1335
- },
1336
- metadata: metadata ? {
1337
- json: metadata
1338
- } : void 0,
1339
- ipAddress: ctx.ipAddress,
1340
- userAgent: ctx.userAgent,
1341
- jurisdiction: input.jurisdiction,
1342
- jurisdictionModel: input.jurisdictionModel,
1343
- tcString: input.tcString,
1344
- uiSource: input.uiSource,
1345
- consentAction: derivedConsentAction,
1346
- givenAt
1347
- });
1348
- logger.debug('Created consent', {
1349
- consentRecord: consentRecord.id
1350
- });
1351
- if (!consentRecord) throw new HTTPException(500, {
1352
- message: 'Failed to create consent',
1353
- cause: {
1354
- code: 'CONSENT_CREATION_FAILED',
1355
- subjectId: subject.id,
1356
- domain
1357
- }
1358
- });
1359
- return {
1360
- consent: consentRecord
1361
- };
1362
- });
1363
- const metrics = getMetrics();
1364
- if (metrics) {
1365
- const jurisdiction = input.jurisdiction;
1366
- metrics.recordConsentCreated({
1367
- type,
1368
- jurisdiction
1369
- });
1370
- const hasAccepted = preferences && Object.values(preferences).some(Boolean);
1371
- if (hasAccepted) metrics.recordConsentAccepted({
1372
- type,
1373
- jurisdiction
1374
- });
1375
- else metrics.recordConsentRejected({
1376
- type,
1377
- jurisdiction
1378
- });
1379
- }
1380
- return c.json({
1381
- subjectId: subject.id,
1382
- consentId: result.consent.id,
1383
- domainId: domainRecord.id,
1384
- domain: domainRecord.name,
1385
- type,
1386
- metadata,
1387
- uiSource: input.uiSource,
1388
- givenAt: result.consent.givenAt
1389
- });
1390
- } catch (error) {
1391
- logger.error('Error in POST /subjects handler', {
1392
- error: extractErrorMessage(error),
1393
- errorType: error instanceof Error ? error.constructor.name : typeof error
1394
- });
1395
- if (error instanceof HTTPException) throw error;
1396
- throw new HTTPException(500, {
1397
- message: 'Internal server error',
1398
- cause: {
1399
- code: 'INTERNAL_SERVER_ERROR'
1400
- }
1401
- });
1402
- }
1403
- };
1404
- const createSubjectRoutes = ()=>{
1405
- const app = new Hono();
1406
- app.get('/:id', describeRoute({
1407
- summary: 'Get subject consent status',
1408
- description: `Returns the subject's consent status for this device. Use to check if the subject has valid consent for given policy types.
1409
-
1410
- **Query:** \`type\` – Filter by consent type(s), comma-separated (e.g. \`privacy_policy,cookie_banner\`).
1411
-
1412
- **Response:** \`subject\`, \`consents\` (matching filter), \`isValid\` (valid consent for requested type(s)).`,
1413
- tags: [
1414
- 'Subject',
1415
- 'Consent'
1416
- ],
1417
- responses: {
1418
- 200: {
1419
- description: 'Subject and consent records for the requested type(s)',
1420
- content: {
1421
- 'application/json': {
1422
- schema: resolver(getSubjectOutputSchema)
1423
- }
1424
- }
1425
- },
1426
- 404: {
1427
- description: 'Subject not found for the given ID'
1428
- }
1429
- }
1430
- }), validator('param', getSubjectInputSchema), getSubjectHandler);
1431
- app.post('/', describeRoute({
1432
- summary: 'Record consent for a subject',
1433
- description: `Creates a new consent record (append-only). Creates the subject if it does not exist.
1434
-
1435
- **Request body by \`type\`:**
1436
- - \`cookie_banner\` – Requires \`preferences\` object
1437
- - \`privacy_policy\`, \`dpa\`, \`terms_and_conditions\` – Optional \`policyId\`
1438
- - \`marketing_communications\`, \`age_verification\`, \`other\` – Optional \`preferences\``,
1439
- tags: [
1440
- 'Subject',
1441
- 'Consent'
1442
- ],
1443
- responses: {
1444
- 200: {
1445
- description: 'Consent recorded; subject and consent in response',
1446
- content: {
1447
- 'application/json': {
1448
- schema: resolver(postSubjectOutputSchema)
1449
- }
1450
- }
1451
- },
1452
- 422: {
1453
- description: 'Invalid request body (schema or validation failed)'
1454
- }
1455
- }
1456
- }), validator('json', postSubjectInputSchema), postSubjectHandler);
1457
- app.patch('/:id', describeRoute({
1458
- summary: 'Link external ID to subject',
1459
- description: 'Associates an external user ID with an existing subject (e.g. after login). Enables cross-device consent sync.',
1460
- tags: [
1461
- 'Subject'
1462
- ],
1463
- responses: {
1464
- 200: {
1465
- description: 'Subject updated with external ID',
1466
- content: {
1467
- 'application/json': {
1468
- schema: resolver(patchSubjectOutputSchema)
1469
- }
1470
- }
1471
- },
1472
- 404: {
1473
- description: 'Subject not found for the given ID'
1474
- }
1475
- }
1476
- }), validator('param', object({
1477
- id: subjectIdSchema
1478
- })), validator('json', object({
1479
- externalId: string(),
1480
- identityProvider: optional(string())
1481
- })), patchSubjectHandler);
1482
- app.get('/', describeRoute({
1483
- summary: 'List subjects by external ID (API key required)',
1484
- description: 'Returns all subjects linked to the given external ID. Requires Bearer token (API key). Use for server-side consent lookups.',
1485
- tags: [
1486
- 'Subject'
1487
- ],
1488
- security: [
1489
- {
1490
- bearerAuth: []
1491
- }
1492
- ],
1493
- responses: {
1494
- 200: {
1495
- description: 'List of subjects for the external ID',
1496
- content: {
1497
- 'application/json': {
1498
- schema: resolver(listSubjectsOutputSchema)
1499
- }
1500
- }
1501
- },
1502
- 401: {
1503
- description: 'Missing or invalid API key'
1504
- }
1505
- }
1506
- }), validator('query', listSubjectsQuerySchema), listSubjectsHandler);
1507
- return app;
1508
- };
1509
- export { createConsentRoutes, createInitRoute, createStatusRoute, createSubjectRoutes };
1
+ export { createConsentRoutes, createInitRoute, createStatusRoute, createSubjectRoutes } from "./364.js";