@geekmidas/constructs 10.0.0-alpha.9 → 10.0.0-alpha.91
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.
- package/README.md +222 -158
- package/dist/{Construct-BD5neF7w.mjs → Construct-B1vGBPme.mjs} +33 -34
- package/dist/Construct-B1vGBPme.mjs.map +1 -0
- package/dist/Construct-BQALFCh2.d.cts +230 -0
- package/dist/Construct-BQALFCh2.d.cts.map +1 -0
- package/dist/{Construct-CyS3RpTL.cjs → Construct-DUSXuTHP.cjs} +53 -48
- package/dist/Construct-DUSXuTHP.cjs.map +1 -0
- package/dist/Construct-QXnl3VqT.d.mts +230 -0
- package/dist/Construct-QXnl3VqT.d.mts.map +1 -0
- package/dist/{Cron-DmQ8vQ4b.d.cts → Cron-DI3nKoic.d.cts} +15 -9
- package/dist/Cron-DI3nKoic.d.cts.map +1 -0
- package/dist/{Cron-dh4rUgib.d.mts → Cron-uYAHPnp7.d.mts} +15 -9
- package/dist/Cron-uYAHPnp7.d.mts.map +1 -0
- package/dist/{CronBuilder-Da0C0edR.cjs → CronBuilder-C0Ek1-RA.cjs} +47 -31
- package/dist/CronBuilder-C0Ek1-RA.cjs.map +1 -0
- package/dist/CronBuilder-DaSUm2Na.d.mts +47 -0
- package/dist/CronBuilder-DaSUm2Na.d.mts.map +1 -0
- package/dist/{CronBuilder-CYKT5RiO.mjs → CronBuilder-Dmix_Pen.mjs} +37 -21
- package/dist/CronBuilder-Dmix_Pen.mjs.map +1 -0
- package/dist/CronBuilder-g1lZLWyG.d.cts +47 -0
- package/dist/CronBuilder-g1lZLWyG.d.cts.map +1 -0
- package/dist/{Endpoint-DCQPMdUX.mjs → Endpoint-BG4UJ9oA.mjs} +146 -109
- package/dist/Endpoint-BG4UJ9oA.mjs.map +1 -0
- package/dist/{Endpoint-DcWXE-SZ.cjs → Endpoint-BoUg8ocM.cjs} +174 -131
- package/dist/Endpoint-BoUg8ocM.cjs.map +1 -0
- package/dist/{Endpoint-BjWKinFA.d.mts → Endpoint-Du-NwPX2.d.mts} +83 -91
- package/dist/Endpoint-Du-NwPX2.d.mts.map +1 -0
- package/dist/{Endpoint-dav89W6-.d.cts → Endpoint-aCvBMPoH.d.cts} +82 -90
- package/dist/Endpoint-aCvBMPoH.d.cts.map +1 -0
- package/dist/{EndpointFactory-CjV8F_lJ.mjs → EndpointFactory-BDtsrEvJ.mjs} +57 -76
- package/dist/EndpointFactory-BDtsrEvJ.mjs.map +1 -0
- package/dist/{EndpointFactory-CdWB7wPw.cjs → EndpointFactory-DJ7gXLpR.cjs} +93 -112
- package/dist/EndpointFactory-DJ7gXLpR.cjs.map +1 -0
- package/dist/{index-Bd5FqCoe.d.cts → EndpointFactory-DMYdJCOj.d.mts} +78 -134
- package/dist/EndpointFactory-DMYdJCOj.d.mts.map +1 -0
- package/dist/{index-lAO9egTb.d.mts → EndpointFactory-I7s1co3Y.d.cts} +79 -135
- package/dist/EndpointFactory-I7s1co3Y.d.cts.map +1 -0
- package/dist/Function-DuqGcbOI.d.mts +76 -0
- package/dist/Function-DuqGcbOI.d.mts.map +1 -0
- package/dist/Function-Pu-1kKZz.d.cts +76 -0
- package/dist/Function-Pu-1kKZz.d.cts.map +1 -0
- package/dist/{HonoEndpointAdaptor-P1ahhZHu.mjs → HonoEndpointAdaptor-PtPlbeKY.mjs} +75 -56
- package/dist/HonoEndpointAdaptor-PtPlbeKY.mjs.map +1 -0
- package/dist/{HonoEndpointAdaptor-DtL9j19R.cjs → HonoEndpointAdaptor-zVzVLJEO.cjs} +83 -61
- package/dist/HonoEndpointAdaptor-zVzVLJEO.cjs.map +1 -0
- package/dist/Queue-A3wfD0it.cjs +109 -0
- package/dist/Queue-A3wfD0it.cjs.map +1 -0
- package/dist/Queue-D6USGS4q.mjs +104 -0
- package/dist/Queue-D6USGS4q.mjs.map +1 -0
- package/dist/{Queue-D7ZuwBhy.d.cts → Queue-DlsHRzUp.d.mts} +48 -48
- package/dist/Queue-DlsHRzUp.d.mts.map +1 -0
- package/dist/{Queue-gVGfi2Yk.d.mts → Queue-HPyi0e1i.d.cts} +49 -49
- package/dist/Queue-HPyi0e1i.d.cts.map +1 -0
- package/dist/QueueBuilder-BjuF0UBl.cjs +135 -0
- package/dist/QueueBuilder-BjuF0UBl.cjs.map +1 -0
- package/dist/QueueBuilder-Cue73M4t.mjs +118 -0
- package/dist/QueueBuilder-Cue73M4t.mjs.map +1 -0
- package/dist/QueueBuilder-OSi6LkV9.d.cts +75 -0
- package/dist/QueueBuilder-OSi6LkV9.d.cts.map +1 -0
- package/dist/QueueBuilder-QHsnVt1P.d.mts +75 -0
- package/dist/QueueBuilder-QHsnVt1P.d.mts.map +1 -0
- package/dist/{Subscriber-2mEi0ImH.d.cts → Subscriber-Bpp02cGr.d.cts} +29 -20
- package/dist/Subscriber-Bpp02cGr.d.cts.map +1 -0
- package/dist/{Subscriber-xTJ9ayPN.d.mts → Subscriber-CtN9R48-.d.mts} +29 -20
- package/dist/Subscriber-CtN9R48-.d.mts.map +1 -0
- package/dist/{SubscriberBuilder-BjkbeT9l.mjs → SubscriberBuilder-CDy4nHCz.mjs} +50 -24
- package/dist/SubscriberBuilder-CDy4nHCz.mjs.map +1 -0
- package/dist/SubscriberBuilder-CuCMFpYW.d.mts +67 -0
- package/dist/SubscriberBuilder-CuCMFpYW.d.mts.map +1 -0
- package/dist/{SubscriberBuilder-4OPehf2R.cjs → SubscriberBuilder-D_owVoHo.cjs} +61 -36
- package/dist/SubscriberBuilder-D_owVoHo.cjs.map +1 -0
- package/dist/SubscriberBuilder-g3fAVWgs.d.cts +67 -0
- package/dist/SubscriberBuilder-g3fAVWgs.d.cts.map +1 -0
- package/dist/Topic-D74b5cgs.mjs +99 -0
- package/dist/Topic-D74b5cgs.mjs.map +1 -0
- package/dist/Topic-GHxcU8AG.cjs +104 -0
- package/dist/Topic-GHxcU8AG.cjs.map +1 -0
- package/dist/adaptors/aws.cjs +131 -220
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts +34 -53
- package/dist/adaptors/aws.d.cts.map +1 -1
- package/dist/adaptors/aws.d.mts +34 -53
- package/dist/adaptors/aws.d.mts.map +1 -1
- package/dist/adaptors/aws.mjs +102 -193
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/hono.cjs +3 -10
- package/dist/adaptors/hono.d.cts +7 -16
- package/dist/adaptors/hono.d.cts.map +1 -1
- package/dist/adaptors/hono.d.mts +8 -17
- package/dist/adaptors/hono.d.mts.map +1 -1
- package/dist/adaptors/hono.mjs +2 -10
- package/dist/adaptors/testing.cjs +743 -89
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +351 -54
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +351 -54
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +706 -70
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/auth-BMCJN30Y.d.cts +268 -0
- package/dist/auth-BMCJN30Y.d.cts.map +1 -0
- package/dist/auth-CcuceLYo.d.mts +268 -0
- package/dist/auth-CcuceLYo.d.mts.map +1 -0
- package/dist/auth.cjs +301 -33
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +2 -108
- package/dist/auth.d.mts +2 -108
- package/dist/auth.mjs +289 -27
- package/dist/auth.mjs.map +1 -1
- package/dist/{cache-BrRz3fEB.d.mts → cache-CXh6GIgb.d.mts} +3 -6
- package/dist/cache-CXh6GIgb.d.mts.map +1 -0
- package/dist/{cache-BtZY_tHe.d.cts → cache-DnGDGly3.d.cts} +3 -6
- package/dist/cache-DnGDGly3.d.cts.map +1 -0
- package/dist/cache.cjs +68 -2
- package/dist/cache.cjs.map +1 -0
- package/dist/cache.d.cts +1 -2
- package/dist/cache.d.mts +1 -2
- package/dist/cache.mjs +67 -2
- package/dist/cache.mjs.map +1 -0
- package/dist/cipher-C1lEFX63.mjs +225 -0
- package/dist/cipher-C1lEFX63.mjs.map +1 -0
- package/dist/cipher-CVxfwLjk.cjs +332 -0
- package/dist/cipher-CVxfwLjk.cjs.map +1 -0
- package/dist/{clone-DblgEZZa.mjs → clone-EKNovYHu.mjs} +3 -3
- package/dist/clone-EKNovYHu.mjs.map +1 -0
- package/dist/{clone-Dy0cR2SZ.cjs → clone-UGJpvQnL.cjs} +7 -8
- package/dist/clone-UGJpvQnL.cjs.map +1 -0
- package/dist/{construct-interface-D9d4Gm4p.d.cts → construct-interface-B1AfqRl4.d.cts} +42 -11
- package/dist/construct-interface-B1AfqRl4.d.cts.map +1 -0
- package/dist/{construct-interface-g5GM5pwR.d.mts → construct-interface-DluK3_da.d.mts} +42 -11
- package/dist/construct-interface-DluK3_da.d.mts.map +1 -0
- package/dist/construct-interface.cjs +113 -7
- package/dist/construct-interface.cjs.map +1 -0
- package/dist/construct-interface.d.cts +2 -2
- package/dist/construct-interface.d.mts +2 -2
- package/dist/construct-interface.mjs +106 -2
- package/dist/construct-interface.mjs.map +1 -0
- package/dist/credential.cjs +77 -17
- package/dist/credential.cjs.map +1 -1
- package/dist/credential.d.cts +34 -9
- package/dist/credential.d.cts.map +1 -1
- package/dist/credential.d.mts +34 -9
- package/dist/credential.d.mts.map +1 -1
- package/dist/credential.mjs +71 -13
- package/dist/credential.mjs.map +1 -1
- package/dist/crons/index.cjs +129 -7
- package/dist/crons/index.cjs.map +1 -1
- package/dist/crons/index.d.cts +45 -11
- package/dist/crons/index.d.cts.map +1 -1
- package/dist/crons/index.d.mts +45 -11
- package/dist/crons/index.d.mts.map +1 -1
- package/dist/crons/index.mjs +127 -8
- package/dist/crons/index.mjs.map +1 -1
- package/dist/database/kysely.cjs +4 -181
- package/dist/database/kysely.d.cts +2 -152
- package/dist/database/kysely.d.mts +2 -152
- package/dist/database/kysely.mjs +2 -180
- package/dist/email.cjs +25 -12
- package/dist/email.cjs.map +1 -1
- package/dist/email.d.cts +3 -7
- package/dist/email.d.cts.map +1 -1
- package/dist/email.d.mts +3 -7
- package/dist/email.d.mts.map +1 -1
- package/dist/email.mjs +16 -3
- package/dist/email.mjs.map +1 -1
- package/dist/encryption.cjs +96 -0
- package/dist/encryption.cjs.map +1 -0
- package/dist/encryption.d.cts +117 -0
- package/dist/encryption.d.cts.map +1 -0
- package/dist/encryption.d.mts +117 -0
- package/dist/encryption.d.mts.map +1 -0
- package/dist/encryption.mjs +83 -0
- package/dist/encryption.mjs.map +1 -0
- package/dist/endpoints/index.cjs +8 -10
- package/dist/endpoints/index.d.cts +51 -7
- package/dist/endpoints/index.d.cts.map +1 -0
- package/dist/endpoints/index.d.mts +51 -7
- package/dist/endpoints/index.d.mts.map +1 -0
- package/dist/endpoints/index.mjs +6 -10
- package/dist/external-api-MJ8id87V.d.mts +105 -0
- package/dist/external-api-MJ8id87V.d.mts.map +1 -0
- package/dist/external-api-O107yzZJ.d.cts +105 -0
- package/dist/external-api-O107yzZJ.d.cts.map +1 -0
- package/dist/external-api.cjs +142 -0
- package/dist/external-api.cjs.map +1 -0
- package/dist/external-api.d.cts +2 -0
- package/dist/external-api.d.mts +2 -0
- package/dist/external-api.mjs +139 -0
- package/dist/external-api.mjs.map +1 -0
- package/dist/file-server.cjs +42 -10
- package/dist/file-server.cjs.map +1 -1
- package/dist/file-server.d.cts +6 -10
- package/dist/file-server.d.cts.map +1 -1
- package/dist/file-server.d.mts +6 -10
- package/dist/file-server.d.mts.map +1 -1
- package/dist/file-server.mjs +34 -2
- package/dist/file-server.mjs.map +1 -1
- package/dist/functions/index.cjs +3 -6
- package/dist/functions/index.d.cts +3 -4
- package/dist/functions/index.d.mts +3 -4
- package/dist/functions/index.mjs +2 -6
- package/dist/{functions-14lpEFL4.mjs → functions-BFizikJU.mjs} +376 -238
- package/dist/{functions-14lpEFL4.mjs.map → functions-BFizikJU.mjs.map} +1 -1
- package/dist/{functions-i_la-N5r.cjs → functions-CfzJG9hK.cjs} +414 -264
- package/dist/functions-CfzJG9hK.cjs.map +1 -0
- package/dist/index-BuzRvKOQ.d.cts +115 -0
- package/dist/index-BuzRvKOQ.d.cts.map +1 -0
- package/dist/index-CTkKOer4.d.mts +115 -0
- package/dist/index-CTkKOer4.d.mts.map +1 -0
- package/dist/index-CeEtxDmK.d.cts +79 -0
- package/dist/index-CeEtxDmK.d.cts.map +1 -0
- package/dist/index-CeEtxDmK.d.mts +79 -0
- package/dist/index-CeEtxDmK.d.mts.map +1 -0
- package/dist/index.cjs +6 -3
- package/dist/index.d.cts +27 -4
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +27 -4
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +3 -3
- package/dist/kms-B-Hm3d5r.cjs +85 -0
- package/dist/kms-B-Hm3d5r.cjs.map +1 -0
- package/dist/kms-BdUlMJEZ.mjs +85 -0
- package/dist/kms-BdUlMJEZ.mjs.map +1 -0
- package/dist/kysely-Bii4l6eP.mjs +370 -0
- package/dist/kysely-Bii4l6eP.mjs.map +1 -0
- package/dist/kysely-CO_Dk43W.cjs +383 -0
- package/dist/kysely-CO_Dk43W.cjs.map +1 -0
- package/dist/kysely-D0bpzgPs.d.cts +175 -0
- package/dist/kysely-D0bpzgPs.d.cts.map +1 -0
- package/dist/kysely-DUqC3Ie0.d.mts +175 -0
- package/dist/kysely-DUqC3Ie0.d.mts.map +1 -0
- package/dist/{telemetry-C3L0iS28.d.cts → lambdaTelemetry-8vnmVZQ5.d.cts} +3 -6
- package/dist/lambdaTelemetry-8vnmVZQ5.d.cts.map +1 -0
- package/dist/{telemetry-D7bVFLGi.d.mts → lambdaTelemetry-8vnmVZQ5.d.mts} +3 -6
- package/dist/lambdaTelemetry-8vnmVZQ5.d.mts.map +1 -0
- package/dist/{lazyAccessors-BoJN3SMd.mjs → lazyAccessors-CFanua0O.mjs} +20 -60
- package/dist/lazyAccessors-CFanua0O.mjs.map +1 -0
- package/dist/{lazyAccessors-e3j2oE2m.cjs → lazyAccessors-hJKGv8Ay.cjs} +60 -113
- package/dist/lazyAccessors-hJKGv8Ay.cjs.map +1 -0
- package/dist/mobile-app.cjs +73 -0
- package/dist/mobile-app.cjs.map +1 -0
- package/dist/mobile-app.d.cts +61 -0
- package/dist/mobile-app.d.cts.map +1 -0
- package/dist/mobile-app.d.mts +61 -0
- package/dist/mobile-app.d.mts.map +1 -0
- package/dist/mobile-app.mjs +72 -0
- package/dist/mobile-app.mjs.map +1 -0
- package/dist/object-storage.cjs +18 -10
- package/dist/object-storage.cjs.map +1 -1
- package/dist/object-storage.d.cts +3 -7
- package/dist/object-storage.d.cts.map +1 -1
- package/dist/object-storage.d.mts +3 -7
- package/dist/object-storage.d.mts.map +1 -1
- package/dist/object-storage.mjs +11 -3
- package/dist/object-storage.mjs.map +1 -1
- package/dist/processAudits-BRRVVHUB.mjs +131 -0
- package/dist/processAudits-BRRVVHUB.mjs.map +1 -0
- package/dist/processAudits-DasOZjPl.cjs +154 -0
- package/dist/processAudits-DasOZjPl.cjs.map +1 -0
- package/dist/queue/index.cjs +6 -189
- package/dist/queue/index.d.cts +3 -60
- package/dist/queue/index.d.mts +3 -60
- package/dist/queue/index.mjs +3 -186
- package/dist/rest-api.cjs +90 -59
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +70 -42
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +70 -42
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +82 -51
- package/dist/rest-api.mjs.map +1 -1
- package/dist/{chunk-DWy1uDak.cjs → rolldown-runtime-y5ARvAq5.cjs} +14 -18
- package/dist/runSubscriber-BHvJ8POr.mjs +109 -0
- package/dist/runSubscriber-BHvJ8POr.mjs.map +1 -0
- package/dist/runSubscriber-D8nLXIv1.cjs +126 -0
- package/dist/runSubscriber-D8nLXIv1.cjs.map +1 -0
- package/dist/shutdown-BMJmAhSt.cjs +38 -0
- package/dist/shutdown-BMJmAhSt.cjs.map +1 -0
- package/dist/shutdown-C7xa8x9S.mjs +27 -0
- package/dist/shutdown-C7xa8x9S.mjs.map +1 -0
- package/dist/site.cjs +33 -7
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +17 -7
- package/dist/site.d.cts.map +1 -1
- package/dist/site.d.mts +17 -7
- package/dist/site.d.mts.map +1 -1
- package/dist/site.mjs +29 -3
- package/dist/site.mjs.map +1 -1
- package/dist/stages-BSCF19o2.d.cts +56 -0
- package/dist/stages-BSCF19o2.d.cts.map +1 -0
- package/dist/stages-BSCF19o2.d.mts +56 -0
- package/dist/stages-BSCF19o2.d.mts.map +1 -0
- package/dist/subscribers/index.cjs +118 -6
- package/dist/subscribers/index.cjs.map +1 -0
- package/dist/subscribers/index.d.cts +51 -6
- package/dist/subscribers/index.d.cts.map +1 -0
- package/dist/subscribers/index.d.mts +51 -6
- package/dist/subscribers/index.d.mts.map +1 -0
- package/dist/subscribers/index.mjs +115 -5
- package/dist/subscribers/index.mjs.map +1 -0
- package/dist/surfaceEnv-CNimK76p.cjs +56 -0
- package/dist/surfaceEnv-CNimK76p.cjs.map +1 -0
- package/dist/surfaceEnv-wMT5QzgZ.mjs +45 -0
- package/dist/surfaceEnv-wMT5QzgZ.mjs.map +1 -0
- package/dist/telemetry-B48RLjyk.d.cts +40 -0
- package/dist/telemetry-B48RLjyk.d.cts.map +1 -0
- package/dist/telemetry-DRtT1_0A.d.mts +40 -0
- package/dist/telemetry-DRtT1_0A.d.mts.map +1 -0
- package/dist/telemetry.cjs +56 -0
- package/dist/telemetry.cjs.map +1 -0
- package/dist/telemetry.d.cts +2 -0
- package/dist/telemetry.d.mts +2 -0
- package/dist/telemetry.mjs +55 -0
- package/dist/telemetry.mjs.map +1 -0
- package/dist/topic/index.cjs +3 -137
- package/dist/topic/index.d.cts +2 -4
- package/dist/topic/index.d.mts +2 -4
- package/dist/topic/index.mjs +2 -134
- package/dist/tracing-CxaZ98IB.mjs +110 -0
- package/dist/tracing-CxaZ98IB.mjs.map +1 -0
- package/dist/tracing-DPMidF_r.cjs +127 -0
- package/dist/tracing-DPMidF_r.cjs.map +1 -0
- package/dist/{types-BlAkSuGI.d.cts → types-DMuSQeLL.d.cts} +3 -5
- package/dist/types-DMuSQeLL.d.cts.map +1 -0
- package/dist/{types-aKksMEWL.d.mts → types-DMuSQeLL.d.mts} +3 -5
- package/dist/types-DMuSQeLL.d.mts.map +1 -0
- package/dist/types.d.cts +1 -1
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +1 -0
- package/dist/worker.cjs +59 -34
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +70 -45
- package/dist/worker.d.cts.map +1 -1
- package/dist/worker.d.mts +70 -44
- package/dist/worker.d.mts.map +1 -1
- package/dist/worker.mjs +54 -29
- package/dist/worker.mjs.map +1 -1
- package/package.json +96 -42
- package/dist/Construct-BD5neF7w.mjs.map +0 -1
- package/dist/Construct-C0ijr2qp.d.cts +0 -117
- package/dist/Construct-C0ijr2qp.d.cts.map +0 -1
- package/dist/Construct-Ct8nalEi.d.mts +0 -117
- package/dist/Construct-Ct8nalEi.d.mts.map +0 -1
- package/dist/Construct-CyS3RpTL.cjs.map +0 -1
- package/dist/Cron-DmQ8vQ4b.d.cts.map +0 -1
- package/dist/Cron-dh4rUgib.d.mts.map +0 -1
- package/dist/CronBuilder-BquXDbDI.d.cts +0 -44
- package/dist/CronBuilder-BquXDbDI.d.cts.map +0 -1
- package/dist/CronBuilder-CGgY2080.d.mts +0 -44
- package/dist/CronBuilder-CGgY2080.d.mts.map +0 -1
- package/dist/CronBuilder-CYKT5RiO.mjs.map +0 -1
- package/dist/CronBuilder-Da0C0edR.cjs.map +0 -1
- package/dist/Endpoint-BjWKinFA.d.mts.map +0 -1
- package/dist/Endpoint-DCQPMdUX.mjs.map +0 -1
- package/dist/Endpoint-DcWXE-SZ.cjs.map +0 -1
- package/dist/Endpoint-dav89W6-.d.cts.map +0 -1
- package/dist/EndpointFactory-CdWB7wPw.cjs.map +0 -1
- package/dist/EndpointFactory-CjV8F_lJ.mjs.map +0 -1
- package/dist/HonoEndpointAdaptor-DtL9j19R.cjs.map +0 -1
- package/dist/HonoEndpointAdaptor-P1ahhZHu.mjs.map +0 -1
- package/dist/Queue-D7ZuwBhy.d.cts.map +0 -1
- package/dist/Queue-gVGfi2Yk.d.mts.map +0 -1
- package/dist/Subscriber-2mEi0ImH.d.cts.map +0 -1
- package/dist/Subscriber-xTJ9ayPN.d.mts.map +0 -1
- package/dist/SubscriberBuilder-4OPehf2R.cjs.map +0 -1
- package/dist/SubscriberBuilder-BjkbeT9l.mjs.map +0 -1
- package/dist/SubscriberBuilder-Dptmo-1A.d.mts +0 -62
- package/dist/SubscriberBuilder-Dptmo-1A.d.mts.map +0 -1
- package/dist/SubscriberBuilder-waNhzjSM.d.cts +0 -62
- package/dist/SubscriberBuilder-waNhzjSM.d.cts.map +0 -1
- package/dist/Topic-19QeHBIR.d.cts +0 -91
- package/dist/Topic-19QeHBIR.d.cts.map +0 -1
- package/dist/Topic-DuFeqkBh.d.mts +0 -91
- package/dist/Topic-DuFeqkBh.d.mts.map +0 -1
- package/dist/auth.d.cts.map +0 -1
- package/dist/auth.d.mts.map +0 -1
- package/dist/cache-0ANvRQnD.mjs +0 -51
- package/dist/cache-0ANvRQnD.mjs.map +0 -1
- package/dist/cache-3WSvAulx.cjs +0 -57
- package/dist/cache-3WSvAulx.cjs.map +0 -1
- package/dist/cache-BrRz3fEB.d.mts.map +0 -1
- package/dist/cache-BtZY_tHe.d.cts.map +0 -1
- package/dist/clone-DblgEZZa.mjs.map +0 -1
- package/dist/clone-Dy0cR2SZ.cjs.map +0 -1
- package/dist/construct-interface-BfjcOD_E.cjs +0 -117
- package/dist/construct-interface-BfjcOD_E.cjs.map +0 -1
- package/dist/construct-interface-D9d4Gm4p.d.cts.map +0 -1
- package/dist/construct-interface-Z4CpS8tK.mjs +0 -81
- package/dist/construct-interface-Z4CpS8tK.mjs.map +0 -1
- package/dist/construct-interface-g5GM5pwR.d.mts.map +0 -1
- package/dist/database/kysely.cjs.map +0 -1
- package/dist/database/kysely.d.cts.map +0 -1
- package/dist/database/kysely.d.mts.map +0 -1
- package/dist/database/kysely.mjs.map +0 -1
- package/dist/functions-i_la-N5r.cjs.map +0 -1
- package/dist/index-Bd5FqCoe.d.cts.map +0 -1
- package/dist/index-BknhM6Ux.d.mts +0 -31
- package/dist/index-BknhM6Ux.d.mts.map +0 -1
- package/dist/index-CBSfrowv.d.cts +0 -31
- package/dist/index-CBSfrowv.d.cts.map +0 -1
- package/dist/index-D24Xm79M.d.cts +0 -171
- package/dist/index-D24Xm79M.d.cts.map +0 -1
- package/dist/index-_ajboYxK.d.mts +0 -171
- package/dist/index-_ajboYxK.d.mts.map +0 -1
- package/dist/index-lAO9egTb.d.mts.map +0 -1
- package/dist/lazyAccessors-BoJN3SMd.mjs.map +0 -1
- package/dist/lazyAccessors-e3j2oE2m.cjs.map +0 -1
- package/dist/processAudits-CGqttuXm.cjs +0 -92
- package/dist/processAudits-CGqttuXm.cjs.map +0 -1
- package/dist/processAudits-Dmts9H_b.mjs +0 -80
- package/dist/processAudits-Dmts9H_b.mjs.map +0 -1
- package/dist/queue/index.cjs.map +0 -1
- package/dist/queue/index.d.cts.map +0 -1
- package/dist/queue/index.d.mts.map +0 -1
- package/dist/queue/index.mjs.map +0 -1
- package/dist/surfaceEnv-BFXEms2f.cjs +0 -39
- package/dist/surfaceEnv-BFXEms2f.cjs.map +0 -1
- package/dist/surfaceEnv-C3Ktahea.mjs +0 -27
- package/dist/surfaceEnv-C3Ktahea.mjs.map +0 -1
- package/dist/telemetry-C3L0iS28.d.cts.map +0 -1
- package/dist/telemetry-D7bVFLGi.d.mts.map +0 -1
- package/dist/topic/index.cjs.map +0 -1
- package/dist/topic/index.mjs.map +0 -1
- package/dist/types-BlAkSuGI.d.cts.map +0 -1
- package/dist/types-aKksMEWL.d.mts.map +0 -1
package/dist/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":["id: ConstructName<TName>","config: BetterAuthConfig<TDatabase>","options: ServiceRegisterOptions","value: string","as: { owner?: boolean }","configured: BetterAuthOptions"],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * `BetterAuth` — a declared auth server.\n *\n * It is three things at once, which is what makes it the construct that\n * exercises most of the model: a consumer of a database, a producer of an\n * authorizer, and a set of endpoints. This lands the first two.\n *\n * Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`\n * — rather than one it invents. The tenant declares the schema and the role;\n * this declares the one thing left, the signing secret, and reads back the keys\n * it needs.\n *\n * :::caution\n * The isolation that arrangement is *for* — the application's own role holding\n * no grant on these tables, so a compromised handler cannot read sessions — does\n * **not hold yet**. No target creates the per-schema role: both connect as the\n * database owner, so today the tenant is a `search_path`, which is a namespace\n * and not a privilege boundary. See \"Roles are declared and never created\" in\n * `docs/design/constructs-outstanding.md`.\n * :::\n *\n * It declares its own surface, so where it answers, who may call it, and the\n * domain its cookies are scoped to all arrive as environment resolved by the\n * target — none of them guessed from a port, and none of them listed by hand in\n * application config.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tenvironmentCase,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { betterAuth } from 'better-auth';\nimport type { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport { type Construct, type Consumable, edgeTo } from './construct-interface';\n\n/** The server better-auth hands back. */\nexport type AuthServer = ReturnType<typeof betterAuth>;\n\n/** Everything better-auth takes, minus what the construct owns. */\nexport type BetterAuthOptions = Omit<\n\tParameters<typeof betterAuth>[0],\n\t'database' | 'secret' | 'basePath' | 'baseURL'\n>;\n\nexport interface BetterAuthConfig<TDatabase extends Consumable> {\n\t/**\n\t * The schema tenant its tables live in.\n\t *\n\t * A construct rather than a URL: the tenant already declares its schema and\n\t * its role, and taking the declaration is what puts the edge in the graph\n\t * instead of a connection string in two places.\n\t */\n\tdatabase: TDatabase;\n\t/**\n\t * The app that serves this auth server, relative to the workspace root —\n\t * `'apps/auth'`.\n\t *\n\t * Required, for the reason `RestApi.path` is. Not to be confused with\n\t * `basePath`, which is where its routes are mounted in a URL.\n\t */\n\tpath: string;\n\t/**\n\t * Where the auth routes are mounted, e.g. `/api/auth`.\n\t *\n\t * Structural — it is part of the URL every client calls, so it cannot differ\n\t * between stages the way the host can.\n\t */\n\tbasePath?: string;\n\t/**\n\t * The rest of better-auth's options: providers, plugins, email settings.\n\t *\n\t * A function when they need another construct — a magic-link plugin has to\n\t * *send* the link, and the thing that sends mail is a construct whose client\n\t * has to be registered. It is handed the same `ServiceRegisterOptions` this\n\t * construct was, so the env parser flows through the graph rather than being\n\t * imported out of application config.\n\t */\n\toptions?:\n\t\t| BetterAuthOptions\n\t\t| ((\n\t\t\t\toptions: ServiceRegisterOptions,\n\t\t ) => BetterAuthOptions | Promise<BetterAuthOptions>);\n}\n\nconst DEFAULT_BASE_PATH = '/api/auth';\n\nexport class BetterAuth<\n\tTName extends string = string,\n\tTDatabase extends Consumable = Consumable,\n> implements Construct<TName, AuthServer>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, AuthServer>;\n\treadonly basePath: string;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the server reads cannot drift.\n\t */\n\tprivate readonly keys: {\n\t\tsecretId: string;\n\t\tsecret: string;\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: BetterAuthConfig<TDatabase>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.basePath = config.basePath ?? DEFAULT_BASE_PATH;\n\n\t\t// A secret's name is its key: `Auth` signs with `AUTH_SECRET`, which is\n\t\t// also what better-auth's own tooling looks for.\n\t\tconst secretId = `${canonical}Secret`;\n\t\tthis.keys = {\n\t\t\tsecretId,\n\t\t\tsecret: environmentCase(secretId),\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\t/**\n\t * A signing secret and a surface.\n\t *\n\t * The database is *not* declared here — the tenant that was passed in\n\t * declares it, and declaring it twice is the duplication the whole model\n\t * removes. What is declared is what this construct owns: the key it signs\n\t * with, and the routes it answers on.\n\t *\n\t * One endpoint, wildcarded. Better Auth routes internally and the set of\n\t * paths depends on which capabilities are enabled, so enumerating them here\n\t * would be a copy of its router that goes stale on its next release. The\n\t * surface's job is to send everything under `basePath` to one handler, which\n\t * is exactly what the declaration says.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'secret',\n\t\t\t\tid: this.keys.secretId,\n\t\t\t\tprovides: [this.keys.secret],\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t\tendpoints: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `${this.id}Handler`,\n\t\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t\tmethod: 'ANY',\n\t\t\t\t\t\tpath: `${this.basePath}/*`,\n\t\t\t\t\t\t// Read off the tenant rather than written down: this\n\t\t\t\t\t\t// construct takes whatever database it is given, and a\n\t\t\t\t\t\t// hardcoded kind is a second statement of a fact the\n\t\t\t\t\t\t// tenant already makes.\n\t\t\t\t\t\tdependencies: [edgeTo(this.config.database)],\n\t\t\t\t\t\trequires: [this.keys.secret],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Better Auth's own migrations, for the app's migrate step.\n\t *\n\t * It brings its own schema — users, sessions, accounts, verifications — so\n\t * the app never writes those tables and never gets to drift from them.\n\t */\n\tasync migrations(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<() => Promise<void>> {\n\t\t// As the owner, not the runtime role. Creating tables is DDL, and the\n\t\t// whole point of the split is that a handler's role cannot do it — so a\n\t\t// migrator that connected the way a handler does would fail on the first\n\t\t// `CREATE TABLE` rather than working by accident.\n\t\tconst auth = await this.connect(options, { owner: true });\n\t\t// better-auth 1.7 split the migration builder out of `better-auth/db`\n\t\t// into its own entry, so importing it no longer drags the whole db layer\n\t\t// in behind it.\n\t\tconst { getMigrations } = await import('better-auth/db/migration');\n\t\tconst { runMigrations } = await getMigrations(auth.options);\n\n\t\treturn runMigrations;\n\t}\n\n\t/**\n\t * The server this surface runs as, built from its own declaration.\n\t *\n\t * A surface is a deploy unit, so something has to serve it, and the thing\n\t * that knows how is the construct — not a generator writing a mount into\n\t * somebody else's entry point. That is how the auth server came to be\n\t * mounted by a hook in the application it was supposed to be separate from,\n\t * and then to be served by nothing at all when the hook was deleted.\n\t *\n\t * The routes come from {@link declare}: one wildcard under `basePath`, read\n\t * off the same declaration the manifest carries, so the surface the graph\n\t * describes and the surface that answers requests cannot disagree.\n\t *\n\t * ```ts\n\t * // .gkm/server/app.ts — the whole generated entry\n\t * import { auth } from '@acme/constructs/auth.js';\n\t * export const { app } = await auth.server({ envParser });\n\t * ```\n\t */\n\tasync server(options: ServiceRegisterOptions): Promise<{ app: Hono }> {\n\t\tconst { Hono } = await import('hono');\n\t\tconst { cors } = await import('hono/cors');\n\t\tconst app = new Hono();\n\t\tconst server = await this.connect(options);\n\n\t\t// Who may call this surface, read off the graph. The same list Better\n\t\t// Auth checks for CSRF — it arrives as `<ID>_TRUSTED_ORIGINS`, composed\n\t\t// by the target from whatever declared an edge to this construct, so a\n\t\t// site that depends on the auth server is allowed to reach it and\n\t\t// nothing else is. Nobody writes an origin down.\n\t\tconst { origins } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tapp.use('*', cors({ origin: origins, credentials: true, maxAge: 3600 }));\n\n\t\t// Read off the declaration rather than restated here. `ANY` is every\n\t\t// method Better Auth routes internally, which is the reason the\n\t\t// declaration wildcards rather than enumerating.\n\t\tconst [surface] = this.declare().filter(\n\t\t\t(d): d is Extract<Declaration, { kind: 'rest-api' }> =>\n\t\t\t\td.kind === 'rest-api',\n\t\t);\n\n\t\tfor (const endpoint of surface?.endpoints ?? []) {\n\t\t\tconst methods =\n\t\t\t\tendpoint.method === 'ANY'\n\t\t\t\t\t? (['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const)\n\t\t\t\t\t: ([endpoint.method] as const);\n\n\t\t\tapp.on([...methods], endpoint.path, (c) => server.handler(c.req.raw));\n\t\t}\n\n\t\treturn { app };\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<AuthServer> {\n\t\tconst { secret, baseUrl, trustedOrigins, cookieDomain } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\tsecret: get(this.keys.secret).string(),\n\t\t\t\t// The surface's own URL, resolved by the target — not guessed from\n\t\t\t\t// a port, which was wrong the moment the server moved to 3001.\n\t\t\t\tbaseUrl: get(this.keys.url).string(),\n\t\t\t\t// Better Auth's CSRF check applies to every caller, not just\n\t\t\t\t// browsers, so an API calling the auth server is rejected unless\n\t\t\t\t// its origin is trusted. The list is derived from the graph and\n\t\t\t\t// arrives as one comma-separated value, for the same reason every\n\t\t\t\t// other derived value arrives as a string: it crosses a process\n\t\t\t\t// boundary as env.\n\t\t\t\ttrustedOrigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t\t// The domain a session cookie has to carry to be readable by a\n\t\t\t\t// frontend on a sibling host. Optional because there is often\n\t\t\t\t// nothing to widen to: locally everything shares `localhost`,\n\t\t\t\t// where cookies ignore the port and a `Domain` would only be a\n\t\t\t\t// value the browser refuses.\n\t\t\t\tcookieDomain: get(this.keys.cookieDomain).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\t// The tenant's own client: one construct, one connection, so what auth\n\t\t// writes and what the browser inspects cannot be two different databases.\n\t\t// A migration asks the tenant for its owner connection, which the tenant\n\t\t// exposes as a `Service` and not as anything `.dependsOn()` would take.\n\t\tconst tenant = this.config.database as Consumable & {\n\t\t\towner?: Service<string, unknown>;\n\t\t};\n\t\tconst source = as.owner && tenant.owner ? tenant.owner : tenant.service;\n\n\t\tconst db = (await source.register(options)) as Kysely<\n\t\t\tRecord<string, never>\n\t\t>;\n\n\t\t// Hoisted: narrowing a property of `this` is not preserved across the\n\t\t// await, and the false branch is the plain-object form.\n\t\tconst configure = this.config.options;\n\t\tconst configured: BetterAuthOptions =\n\t\t\ttypeof configure === 'function'\n\t\t\t\t? await configure(options)\n\t\t\t\t: (configure ?? {});\n\n\t\t// `Auth<O>` is invariant in its options in better-auth 1.7, so the value\n\t\t// built from a concrete literal is not assignable to the `AuthServer`\n\t\t// alias, which names the constraint. The runtime object is the same one\n\t\t// either way; the assertion keeps the variance where it happens instead\n\t\t// of spreading a generic through the construct's public type.\n\t\treturn betterAuth({\n\t\t\t...configured,\n\t\t\tsecret,\n\t\t\tbaseURL: baseUrl,\n\t\t\tbasePath: this.basePath,\n\t\t\tdatabase: { db, type: 'postgres' },\n\t\t\t// Whatever the app added wins over the derived list rather than\n\t\t\t// replacing it: an origin nobody declared is still sometimes real.\n\t\t\ttrustedOrigins: [\n\t\t\t\t...trustedOrigins,\n\t\t\t\t...(configured.trustedOrigins &&\n\t\t\t\tArray.isArray(configured.trustedOrigins)\n\t\t\t\t\t? configured.trustedOrigins\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tadvanced: {\n\t\t\t\t...configured.advanced,\n\t\t\t\t// Only when a domain was derived. Better Auth reads the presence\n\t\t\t\t// of this block as intent, so enabling it with no domain would\n\t\t\t\t// widen the cookie to whatever host happened to set it — and the\n\t\t\t\t// case with nothing to widen to is the common one, not an error.\n\t\t\t\t...(cookieDomain\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcrossSubDomainCookies: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tdomain: cookieDomain,\n\t\t\t\t\t\t\t\t...configured.advanced?.crossSubDomainCookies,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t}) as AuthServer;\n\t}\n}\n"],"mappings":";;;;;AA0FA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAIA;CACC,AAAS;CACT,AAAS;CACT,AAAS;;;;;CAMT,AAAiB;CAQjB,YACCA,IACiBC,QAChB;EADgB;EAEjB,MAAM,YAAY,YAAY,GAAa;AAE3C,OAAK,KAAK;AACV,OAAK,WAAW,OAAO,YAAY;EAInC,MAAM,YAAY,EAAE,UAAU;AAC9B,OAAK,OAAO;GACX;GACA,QAAQ,gBAAgB,SAAS;GACjC,KAAK,WAAW,WAAW,MAAM;GACjC,gBAAgB,WAAW,WAAW,iBAAiB;GACvD,cAAc,WA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AAOpB,SAAO,WAAW;GACjB,GAAG;GACH;GACA,SAAS;GACT,UAAU,KAAK;GACf,UAAU;IAAE;IAAI,MAAM;GAAY;GAGlC,gBAAgB,CACf,GAAG,gBACH,GAAI,WAAW,kBACf,MAAM,QAAQ,WAAW,eAAe,GACrC,WAAW,iBACX,CAAE,CACL;GACD,UAAU;IACT,GAAG,WAAW;IAKd,GAAI,eACD,EACA,uBAAuB;KACtB,SAAS;KACT,QAAQ;KACR,GAAG,WAAW,UAAU;IACxB,EACD,IACA,CAAE;GACL;EACD,EAAC;CACF;AACD"}
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * `BetterAuth` — a declared auth server.\n *\n * It is three things at once, which is what makes it the construct that\n * exercises most of the model: a consumer of a database, a producer of an\n * authorizer, and a set of endpoints. This lands the first two.\n *\n * Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`\n * — rather than one it invents. The tenant declares the schema and the role;\n * this declares the one thing left, the signing secret, and reads back the keys\n * it needs.\n *\n * :::caution\n * The isolation that arrangement is *for* — the application's own role holding\n * no grant on these tables, so a compromised handler cannot read sessions — does\n * **not hold yet**. No target creates the per-schema role: both connect as the\n * database owner, so today the tenant is a `search_path`, which is a namespace\n * and not a privilege boundary. See \"Roles are declared and never created\" in\n * `docs/design/constructs-outstanding.md`.\n * :::\n *\n * It declares its own surface, so where it answers, who may call it, and the\n * domain its cookies are scoped to all arrive as environment resolved by the\n * target — none of them guessed from a port, and none of them listed by hand in\n * application config.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\tCLIENT_IP_HEADER,\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tenvironmentCase,\n\tisWebOrigin,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type {\n\tService,\n\tServiceRecord,\n\tServiceRegisterOptions,\n} from '@geekmidas/services';\n// Types only: the server is built in `connect()`, from a dynamic import, so a\n// process that only holds the client never loads better-auth to get it.\nimport type { betterAuth } from 'better-auth';\nimport type { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport {\n\ttype Authenticator,\n\ttype Construct,\n\ttype Consumable,\n\tedgeTo,\n\ttype ServicesOf,\n} from './construct-interface';\nimport type { Telemetry } from './telemetry';\nimport { injectTraceContext } from './tracing';\n\n/** The server better-auth hands back. */\nexport type AuthServer = ReturnType<typeof betterAuth>;\n\n/** A signed-in session as better-auth hands it back: `{ user, session }`. */\nexport type AuthSession = AuthServer['$Infer']['Session'];\n\n/**\n * What `.dependsOn([auth])` hands a handler: the auth server, over HTTP.\n *\n * The server itself — its secret, its tenant's connection, its mailer — lives\n * in the auth app's own process and nowhere else. Every other process is a\n * caller of it, so what it is given is an address and this, with the one\n * call handlers make kept in Better Auth's shape: `api.getSession({ headers })`\n * answers `{ user, session }` or `null`, as the server's own `api` does.\n */\nexport interface AuthClient {\n\treadonly api: {\n\t\t/**\n\t\t * The session the request's cookie or bearer token belongs to, or `null`\n\t\t * when there is none — asked of `<basePath>/get-session` at the auth\n\t\t * server's URL. Only `cookie` and `authorization` are forwarded, with\n\t\t * the client's address as `x-gkm-client-ip` (read from the request's\n\t\t * `x-forwarded-for`) and the active trace context.\n\t\t *\n\t\t * @throws {AuthServerUnreachable} when the request does not get there.\n\t\t * @throws {SessionCheckFailed} when the server answers with a failure.\n\t\t */\n\t\tgetSession(input: {\n\t\t\theaders: ConstructorParameters<typeof Headers>[0];\n\t\t}): Promise<AuthSession | null>;\n\t};\n}\n\n/** Everything better-auth takes, minus what the construct owns. */\nexport type BetterAuthOptions = Omit<\n\tParameters<typeof betterAuth>[0],\n\t'database' | 'secret' | 'basePath' | 'baseURL'\n>;\n\n/**\n * What an `options` callback is handed: the options this construct was\n * registered with, and a client for each construct its `dependsOn` names —\n * keyed by service name, exactly as an endpoint's handler receives them.\n */\nexport type BetterAuthOptionsContext<TUses extends readonly Consumable[]> =\n\tServiceRegisterOptions & {\n\t\tservices: ServiceRecord<[...ServicesOf<TUses>]>;\n\t};\n\nexport interface BetterAuthConfig<\n\tTDatabase extends Consumable,\n\tTUses extends readonly Consumable[] = readonly [],\n> {\n\t/**\n\t * The schema tenant its tables live in.\n\t *\n\t * A construct rather than a URL: the tenant already declares its schema and\n\t * its role, and taking the declaration is what puts the edge in the graph\n\t * instead of a connection string in two places.\n\t */\n\tdatabase: TDatabase;\n\t/**\n\t * The app that serves this auth server, relative to the workspace root —\n\t * `'apps/auth'`.\n\t *\n\t * Required, for the reason `RestApi.path` is. Not to be confused with\n\t * `basePath`, which is where its routes are mounted in a URL.\n\t */\n\tpath: string;\n\t/**\n\t * The label it answers on under a stage's domain — `api` for\n\t * `api.myapp.com`, from `domains` — and under the project locally,\n\t * `api.myapp.localhost`. Absent, its id kebab-cased.\n\t */\n\tsubdomain?: string;\n\t/**\n\t * Where the auth routes are mounted, e.g. `/api/auth`.\n\t *\n\t * Structural — it is part of the URL every client calls, so it cannot differ\n\t * between stages the way the host can.\n\t */\n\tbasePath?: string;\n\t/**\n\t * The constructs `options` uses — the mailer a magic link goes through,\n\t * most often.\n\t *\n\t * One list, two jobs, the way an endpoint's `.dependsOn()` has: each is an\n\t * edge on the server's handler, so whatever is composed from the edges (a\n\t * container's environment, a deploy's grants) includes it; and each is\n\t * handed to `options` as a client in `services`, so there is no other way\n\t * for `options` to reach it — nothing to import and register by hand, and\n\t * so nothing that can be used without being declared.\n\t */\n\tdependsOn?: TUses;\n\t/**\n\t * What the auth server's process emits — the `Telemetry` construct, passed\n\t * like a `RestApi`'s. An edge to the node: the deploy hands the process the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * The rest of better-auth's options: providers, plugins, email settings.\n\t *\n\t * A function when they need another construct — a magic-link plugin has to\n\t * *send* the link. It is handed the options this construct was registered\n\t * with, and `services`: a client for each construct in `dependsOn`.\n\t */\n\toptions?:\n\t\t| BetterAuthOptions\n\t\t| ((\n\t\t\t\tcontext: BetterAuthOptionsContext<TUses>,\n\t\t ) => BetterAuthOptions | Promise<BetterAuthOptions>);\n}\n\nconst DEFAULT_BASE_PATH = '/api/auth';\n\nexport class BetterAuth<\n\tTName extends string = string,\n\tTDatabase extends Consumable = Consumable,\n\tconst TUses extends readonly Consumable[] = readonly [],\n> implements Construct<TName, AuthClient>, Authenticator<AuthSession>\n{\n\treadonly id: TName;\n\t/**\n\t * What `.dependsOn([auth])` injects: an {@link AuthClient}, never the server.\n\t *\n\t * Which of the two a process holds is decided by how it reaches the\n\t * construct, not by asking where it is running. The auth app's process is\n\t * its generated entry, which calls {@link server} and nothing else — a\n\t * self-serving surface has no endpoints of its own for a `dependsOn` to sit\n\t * on. Every other process reaches it through this. So the API, a worker, a\n\t * test's in-process endpoints all get the client, and none of them needs\n\t * the signing secret, the auth tenant's URL or the mailer to start.\n\t */\n\treadonly service: Service<Uncapitalize<TName>, AuthClient>;\n\treadonly basePath: string;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the server reads cannot drift.\n\t */\n\tprivate readonly keys: {\n\t\tsecretId: string;\n\t\tsecret: string;\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: BetterAuthConfig<TDatabase, TUses>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.basePath = config.basePath ?? DEFAULT_BASE_PATH;\n\n\t\t// A secret's name is its key: `Auth` signs with `AUTH_SECRET`, which is\n\t\t// also what better-auth's own tooling looks for.\n\t\tconst secretId = `${canonical}Secret`;\n\t\tthis.keys = {\n\t\t\tsecretId,\n\t\t\tsecret: environmentCase(secretId),\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.client(options.envParser),\n\t\t};\n\t}\n\n\t/**\n\t * A signing secret and a surface.\n\t *\n\t * The database is *not* declared here — the tenant that was passed in\n\t * declares it, and declaring it twice is the duplication the whole model\n\t * removes. What is declared is what this construct owns: the key it signs\n\t * with, and the routes it answers on.\n\t *\n\t * One endpoint, wildcarded. Better Auth routes internally and the set of\n\t * paths depends on which capabilities are enabled, so enumerating them here\n\t * would be a copy of its router that goes stale on its next release. The\n\t * surface's job is to send everything under `basePath` to one handler, which\n\t * is exactly what the declaration says.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'secret',\n\t\t\t\tid: this.keys.secretId,\n\t\t\t\tprovides: [this.keys.secret],\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\t...(this.config.subdomain ? { subdomain: this.config.subdomain } : {}),\n\t\t\t\t...(this.config.telemetry\n\t\t\t\t\t? { telemetry: this.config.telemetry.id }\n\t\t\t\t\t: {}),\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t\tendpoints: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `${this.id}Handler`,\n\t\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t\tmethod: 'ANY',\n\t\t\t\t\t\tpath: `${this.basePath}/*`,\n\t\t\t\t\t\t// Read off the tenant rather than written down: this\n\t\t\t\t\t\t// construct takes whatever database it is given, and a\n\t\t\t\t\t\t// hardcoded kind is a second statement of a fact the\n\t\t\t\t\t\t// tenant already makes.\n\t\t\t\t\t\tdependencies: [\n\t\t\t\t\t\t\tedgeTo(this.config.database),\n\t\t\t\t\t\t\t...(this.config.dependsOn ?? []).map(edgeTo),\n\t\t\t\t\t\t],\n\t\t\t\t\t\trequires: [this.keys.secret],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Whose request this is: the session for these headers, or `null`.\n\t *\n\t * Asked of the auth server over HTTP, at the URL the `.auth()` edge injects —\n\t * so it is the same call whether the server runs in this process, beside\n\t * it, or behind MSW in a test. The same call {@link AuthClient} makes.\n\t */\n\tasync verify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<AuthSession | null> {\n\t\treturn this.client(envParser).api.getSession({ headers });\n\t}\n\n\t/**\n\t * The client a caller of this server holds: its URL and nothing else.\n\t *\n\t * `<ID>_URL` is the one key a consumer is given for an edge to a surface —\n\t * the compose network's address between containers, the public one where\n\t * that is all there is — so this is everything it can know.\n\t */\n\tclient(envParser: EnvironmentParser<{}>): AuthClient {\n\t\tconst { url } = envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\t\tconst endpoint = `${url.replace(/\\/$/, '')}${this.basePath}`;\n\n\t\treturn {\n\t\t\tapi: {\n\t\t\t\tgetSession: ({ headers }) =>\n\t\t\t\t\tfetchSession(this.id, endpoint, new Headers(headers)),\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * The tenant this server keeps its tables in — whose migrations folder,\n\t * `db/<tenant>/`, Better Auth's schema is written into.\n\t */\n\tget databaseId(): string {\n\t\treturn this.config.database.id;\n\t}\n\n\t/**\n\t * The SQL that brings the tenant up to Better Auth's schema, or `undefined`\n\t * when it already matches.\n\t *\n\t * What `gkm migration` writes as the tenant's next migration, so Better\n\t * Auth's tables are committed, reviewed and applied like any other — rather\n\t * than diffed against the database at runtime, where a change nobody wrote\n\t * down happens on whichever machine migrates first.\n\t *\n\t * Compared as the owner, against the tenant `gkm migrate` has already brought\n\t * up to date: what comes back is only what the committed files are missing.\n\t */\n\tasync pendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined> {\n\t\t// The options, not a server built from them: better-auth checks its\n\t\t// schema when a server starts, and before the migration that creates the\n\t\t// tables it can only report them missing.\n\t\tconst resolved = await this.optionsFor(options, { owner: true });\n\t\tconst db = (resolved.database as { db: Kysely<Record<string, never>> }).db;\n\n\t\ttry {\n\t\t\t// better-auth 1.7 split the migration builder out of `better-auth/db`\n\t\t\t// into its own entry, so importing it no longer drags the whole db\n\t\t\t// layer in behind it.\n\t\t\tconst { getMigrations } = await import('better-auth/db/migration');\n\t\t\tconst { toBeCreated, toBeAdded, toBeAddedIndexes, compileMigrations } =\n\t\t\t\tawait getMigrations(resolved);\n\n\t\t\tif (\n\t\t\t\ttoBeCreated.length === 0 &&\n\t\t\t\ttoBeAdded.length === 0 &&\n\t\t\t\ttoBeAddedIndexes.length === 0\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\treturn idempotent(await compileMigrations());\n\t\t} finally {\n\t\t\t// Its own pool: left open, it keeps the process that asked alive.\n\t\t\tawait db.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * The server this surface runs as, built from its own declaration.\n\t *\n\t * A surface is a deploy unit, so something has to serve it, and the thing\n\t * that knows how is the construct — not a generator writing a mount into\n\t * somebody else's entry point. That is how the auth server came to be\n\t * mounted by a hook in the application it was supposed to be separate from,\n\t * and then to be served by nothing at all when the hook was deleted.\n\t *\n\t * The routes come from {@link declare}: one wildcard under `basePath`, read\n\t * off the same declaration the manifest carries, so the surface the graph\n\t * describes and the surface that answers requests cannot disagree.\n\t *\n\t * ```ts\n\t * // .gkm/server/app.ts — the whole generated entry\n\t * import { auth } from '@acme/constructs/auth.js';\n\t * export const { app } = await auth.server({ envParser });\n\t * ```\n\t *\n\t * The only way to the server: it is what reads the signing secret, opens\n\t * the tenant and builds the mailer, so it is built here, in the auth app's\n\t * own process, and `.dependsOn([auth])` everywhere else gets\n\t * {@link AuthClient}. `auth` is the better-auth instance behind the app.\n\t */\n\tasync server(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<{ app: Hono; auth: AuthServer }> {\n\t\tconst { Hono } = await import('hono');\n\t\tconst { cors } = await import('hono/cors');\n\t\tconst app = new Hono();\n\t\tconst server = await this.connect(options);\n\n\t\t// Who may call this surface, read off the graph. The same list Better\n\t\t// Auth checks for CSRF — it arrives as `<ID>_TRUSTED_ORIGINS`, composed\n\t\t// by the target from whatever declared an edge to this construct, so a\n\t\t// site that depends on the auth server is allowed to reach it and\n\t\t// nothing else is. Nobody writes an origin down.\n\t\tconst { origins } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tapp.use('*', cors({ origin: origins, credentials: true, maxAge: 3600 }));\n\n\t\t// Read off the declaration rather than restated here. `ANY` is every\n\t\t// method Better Auth routes internally, which is the reason the\n\t\t// declaration wildcards rather than enumerating.\n\t\tconst [surface] = this.declare().filter(\n\t\t\t(d): d is Extract<Declaration, { kind: 'rest-api' }> =>\n\t\t\t\td.kind === 'rest-api',\n\t\t);\n\n\t\tfor (const endpoint of surface?.endpoints ?? []) {\n\t\t\tconst methods =\n\t\t\t\tendpoint.method === 'ANY'\n\t\t\t\t\t? (['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const)\n\t\t\t\t\t: ([endpoint.method] as const);\n\n\t\t\tapp.on([...methods], endpoint.path, (c) =>\n\t\t\t\tserver.handler(withTrustedClientIp(c.req.raw, remoteAddressOf(c))),\n\t\t\t);\n\t\t}\n\n\t\treturn { app, auth: server };\n\t}\n\n\t/**\n\t * The ids of the better-auth plugins this server runs — what a client has\n\t * to pair its own plugins with (`magic-link` with `magicLinkClient`).\n\t * Resolved the way the server resolves them, options callback included.\n\t */\n\tasync pluginIds(options: ServiceRegisterOptions): Promise<string[]> {\n\t\tconst { plugins = [] } = await this.configured(options);\n\t\treturn plugins.map(({ id }) => id);\n\t}\n\n\t/** Better-auth's options as given — a value, or a callback of the environment. */\n\tprivate async configured(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<BetterAuthOptions> {\n\t\t// Hoisted: narrowing a property of `this` is not preserved across the\n\t\t// await, and the false branch is the plain-object form.\n\t\tconst configure = this.config.options;\n\t\tif (typeof configure !== 'function') return configure ?? {};\n\n\t\t// A client for each declared construct, from the options this call was\n\t\t// given — not the process-wide discovery, which keeps whichever env\n\t\t// parser reached it first.\n\t\tconst services: Record<string, unknown> = {};\n\t\tfor (const construct of this.config.dependsOn ?? []) {\n\t\t\tservices[construct.service.serviceName] =\n\t\t\t\tawait construct.service.register(options);\n\t\t}\n\n\t\treturn configure({\n\t\t\t...options,\n\t\t\tservices,\n\t\t} as BetterAuthOptionsContext<TUses>);\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<AuthServer> {\n\t\tconst { betterAuth } = await import('better-auth');\n\t\t// `Auth<O>` is invariant in its options in better-auth 1.7, so the value\n\t\t// built from a concrete literal is not assignable to the `AuthServer`\n\t\t// alias, which names the constraint. The runtime object is the same one\n\t\t// either way; the assertion keeps the variance where it happens instead\n\t\t// of spreading a generic through the construct's public type.\n\t\treturn betterAuth(await this.optionsFor(options, as)) as AuthServer;\n\t}\n\n\t/**\n\t * Everything better-auth is given: the app's options, and what the construct\n\t * owns — its secret, its URL, its tenant's connection, the origins and cookie\n\t * domain its graph derives. One place, so the server and its migrations are\n\t * built from the same options.\n\t */\n\tprivate async optionsFor(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Parameters<typeof betterAuth>[0]> {\n\t\tconst { secret, baseUrl, trustedOrigins, cookieDomain, deviceUrl } =\n\t\t\toptions.envParser\n\t\t\t\t.create((get) => ({\n\t\t\t\t\tsecret: get(this.keys.secret).string(),\n\t\t\t\t\t// The surface's own URL, resolved by the target — not guessed from\n\t\t\t\t\t// a port, which was wrong the moment the server moved to 3001.\n\t\t\t\t\tbaseUrl: get(this.keys.url).string(),\n\t\t\t\t\t// Better Auth's CSRF check applies to every caller, not just\n\t\t\t\t\t// browsers, so an API calling the auth server is rejected unless\n\t\t\t\t\t// its origin is trusted. The list is derived from the graph and\n\t\t\t\t\t// arrives as one comma-separated value, for the same reason every\n\t\t\t\t\t// other derived value arrives as a string: it crosses a process\n\t\t\t\t\t// boundary as env.\n\t\t\t\t\ttrustedOrigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.default('')\n\t\t\t\t\t\t.transform((value) =>\n\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t\t),\n\t\t\t\t\t// The domain a session cookie has to carry to be readable by a\n\t\t\t\t\t// frontend on a sibling host. Optional because there is often\n\t\t\t\t\t// nothing to widen to: locally everything shares `localhost`,\n\t\t\t\t\t// where cookies ignore the port and a `Domain` would only be a\n\t\t\t\t\t// value the browser refuses.\n\t\t\t\t\tcookieDomain: get(this.keys.cookieDomain).string().optional(),\n\t\t\t\t\t// Where a phone reaches this server, on a local stage with a mobile\n\t\t\t\t\t// app: its own port on the LAN address. Never deployed.\n\t\t\t\t\tdeviceUrl: get(provideKey(this.id, 'deviceUrl')).string().optional(),\n\t\t\t\t}))\n\t\t\t\t.parse();\n\n\t\t// The tenant's own client: one construct, one connection, so what auth\n\t\t// writes and what the browser inspects cannot be two different databases.\n\t\t// A migration asks the tenant for its owner connection, which the tenant\n\t\t// exposes as a `Service` and not as anything `.dependsOn()` would take.\n\t\tconst tenant = this.config.database as Consumable & {\n\t\t\towner?: Service<string, unknown>;\n\t\t};\n\t\tconst source = as.owner && tenant.owner ? tenant.owner : tenant.service;\n\n\t\tconst db = (await source.register(options)) as Kysely<\n\t\t\tRecord<string, never>\n\t\t>;\n\n\t\tconst configured = await this.configured(options);\n\n\t\t// Whatever the app added wins over the derived list rather than\n\t\t// replacing it: an origin nobody declared is still sometimes real.\n\t\tconst origins = [\n\t\t\t...trustedOrigins,\n\t\t\t...(configured.trustedOrigins && Array.isArray(configured.trustedOrigins)\n\t\t\t\t? configured.trustedOrigins\n\t\t\t\t: []),\n\t\t];\n\n\t\tconst plugins = [...(configured.plugins ?? [])];\n\t\t// A mobile app depends on this server: the graph put its scheme among\n\t\t// the derived origins. It signs in through Better Auth's Expo plugin —\n\t\t// the app sends its scheme as the origin, and the plugin is what reads\n\t\t// it — so a server without it would refuse every request the app made.\n\t\t// Asked of the app rather than imported here: a package this one\n\t\t// imported would have to be its peer, and an optional peer gives every\n\t\t// differently-resolving workspace package its own copy of this one.\n\t\tconst mobile = trustedOrigins.filter((origin) => !isWebOrigin(origin));\n\t\tif (mobile.length > 0 && !plugins.some((plugin) => plugin.id === 'expo')) {\n\t\t\tthrow new ExpoPluginRequired(this.id, mobile);\n\t\t}\n\t\t// A sign-in link the app asked for is opened on the phone, which cannot\n\t\t// resolve this server's local hostname; on a local stage it is built on\n\t\t// the address the phone reaches it on instead.\n\t\tif (deviceUrl) {\n\t\t\tfor (const plugin of plugins) reachableFromDevice(plugin, deviceUrl);\n\t\t}\n\n\t\treturn {\n\t\t\t...configured,\n\t\t\tsecret,\n\t\t\tbaseURL: baseUrl,\n\t\t\tbasePath: this.basePath,\n\t\t\tdatabase: { db, type: 'postgres' },\n\t\t\tplugins,\n\t\t\ttrustedOrigins: origins,\n\t\t\tadvanced: {\n\t\t\t\t...configured.advanced,\n\t\t\t\t// The client's address on a call from one of this stack's own\n\t\t\t\t// services comes in gkm's header, ahead of whatever the app reads\n\t\t\t\t// otherwise — `X-Forwarded-For` by default, as Better Auth reads a\n\t\t\t\t// request that reached it through a proxy. The header is honoured\n\t\t\t\t// only from an internal caller: see `withTrustedClientIp`.\n\t\t\t\tipAddress: {\n\t\t\t\t\t...configured.advanced?.ipAddress,\n\t\t\t\t\tipAddressHeaders: [\n\t\t\t\t\t\tCLIENT_IP_HEADER,\n\t\t\t\t\t\t...(\n\t\t\t\t\t\t\tconfigured.advanced?.ipAddress?.ipAddressHeaders ?? [\n\t\t\t\t\t\t\t\t'x-forwarded-for',\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t).filter((name) => name.toLowerCase() !== CLIENT_IP_HEADER),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t// Only when a domain was derived. Better Auth reads the presence\n\t\t\t\t// of this block as intent, so enabling it with no domain would\n\t\t\t\t// widen the cookie to whatever host happened to set it — and the\n\t\t\t\t// case with nothing to widen to is the common one, not an error.\n\t\t\t\t...(cookieDomain\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcrossSubDomainCookies: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tdomain: cookieDomain,\n\t\t\t\t\t\t\t\t...configured.advanced?.crossSubDomainCookies,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Links already rewritten — an `options` object is reused across builds. */\nconst rewritten = new WeakSet<object>();\n\n/**\n * Build the magic links an app asked for on the address a phone reaches.\n *\n * An app's link carries its scheme as the `callbackURL` (`shop://…`)\n * where a browser's carries a path or an `http(s)` URL — which is how the two\n * are told apart. A browser's link is left alone: it is opened on this\n * machine, where the server's own hostname resolves.\n *\n * Better Auth's magic-link plugin calls `sendMagicLink` through the options\n * object it returns, so wrapping it there is wrapping the call.\n */\nfunction reachableFromDevice(plugin: { id: string }, deviceUrl: string): void {\n\tif (plugin.id !== 'magic-link') return;\n\tconst options = (plugin as { options?: MagicLinkOptions }).options;\n\tif (!options?.sendMagicLink || rewritten.has(options)) return;\n\trewritten.add(options);\n\n\tconst send = options.sendMagicLink;\n\toptions.sendMagicLink = (data, ...rest) =>\n\t\tsend({ ...data, url: deviceLink(data.url, deviceUrl) }, ...rest);\n}\n\ninterface MagicLinkOptions {\n\tsendMagicLink?: (\n\t\tdata: { email: string; url: string; token: string },\n\t\t...rest: unknown[]\n\t) => unknown;\n}\n\n/** A magic link moved to the device address when an app is its destination. */\nexport function deviceLink(url: string, deviceUrl: string): string {\n\ttry {\n\t\tconst link = new URL(url);\n\t\tconst callback = link.searchParams.get('callbackURL') ?? '/';\n\t\tif (callback.startsWith('/') || isWebOrigin(callback)) return url;\n\t\treturn new URL(`${link.pathname}${link.search}`, deviceUrl).toString();\n\t} catch {\n\t\treturn url;\n\t}\n}\n\n/** A mobile app depends on this auth server, which has no Expo plugin. */\nexport class ExpoPluginRequired extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\t/** The schemes the graph says call it — what made the plugin necessary. */\n\t\treadonly origins: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' is called by a mobile app (${origins[0]}), and a mobile app ` +\n\t\t\t\t`signs in through Better Auth's Expo plugin: add expo() from ` +\n\t\t\t\t`'@better-auth/expo' to this auth server's plugins.`,\n\t\t);\n\t\tthis.name = 'ExpoPluginRequired';\n\t}\n}\n\n/** What is forwarded to the auth server: the headers a session travels in. */\nconst SESSION_HEADERS = ['cookie', 'authorization'] as const;\n\n/**\n * `GET <basePath>/get-session`, read the way Better Auth answers it.\n *\n * Whose request it is travels in {@link CLIENT_IP_HEADER} — the server\n * rate-limits `/get-session` by the client's address, so without it every\n * caller shares the API's one bucket — and never as `X-Forwarded-For`. A\n * forwarding header is what marks a request as outside traffic, so the auth\n * server would start its span in a trace of its own rather than continue the\n * API's. Without one, this is an internal caller's request, and the trace\n * context it carries is continued.\n */\nasync function fetchSession(\n\tauthenticator: string,\n\tendpoint: string,\n\tgiven: Headers,\n): Promise<AuthSession | null> {\n\tconst headers = new Headers();\n\tfor (const name of SESSION_HEADERS) {\n\t\tconst value = given.get(name);\n\t\tif (value) headers.set(name, value);\n\t}\n\t// The chain as the API received it, so the auth server reads it exactly\n\t// as it would have read `X-Forwarded-For` (its `trustedProxies` included).\n\t// Never a `CLIENT_IP_HEADER` the API was sent: this process cannot tell\n\t// here whether its own caller was internal, and the auth server trusts\n\t// whatever an internal caller — this one — says.\n\tconst client = given.get('x-forwarded-for');\n\tif (client) headers.set(CLIENT_IP_HEADER, client);\n\tinjectTraceContext(headers);\n\n\tconst url = `${endpoint}/get-session`;\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, { headers });\n\t} catch (cause) {\n\t\tthrow new AuthServerUnreachable(authenticator, url, cause);\n\t}\n\n\t// Better Auth answers `null` for a request with no session, and a 401 is\n\t// the same answer from anything in front of it. Anything else that is not\n\t// a 200 is the server failing, which is not \"signed out\" and must not be\n\t// read as it.\n\tif (response.status === 401) return null;\n\tif (!response.ok) {\n\t\tthrow new SessionCheckFailed(authenticator, response.status);\n\t}\n\n\treturn (await response.json()) as AuthSession | null;\n}\n\n/** The auth server answered a session check with a failure. */\nexport class SessionCheckFailed extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' answered a session check with ${status}. ` +\n\t\t\t\t`A request with no session gets 200 and null, or 401; this is the ` +\n\t\t\t\t`server failing — check its logs, and that it is running at its URL.`,\n\t\t);\n\t\tthis.name = 'SessionCheckFailed';\n\t}\n}\n\n/** A session check never reached the auth server. */\nexport class AuthServerUnreachable extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly url: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' could not be reached at ${url} to check a session. ` +\n\t\t\t\t`Check that the auth app is running and that this app's ` +\n\t\t\t\t`${provideKey(authenticator, 'url')} points at it.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'AuthServerUnreachable';\n\t}\n}\n\n/**\n * Better Auth's DDL, safe to run where its tables already exist.\n *\n * Its SQL is Kysely's, so its shape is known: `create table \"…\"`, `create index\n * \"…\"`, `alter table \"…\" add column \"…\"`. A database that has been running\n * already has those — Better Auth used to create them at runtime — and the\n * first committed migration would fail on them rather than recording that they\n * are there.\n */\nexport function idempotent(statements: string): string {\n\treturn statements\n\t\t.replace(/\\bcreate table \"/gi, 'create table if not exists \"')\n\t\t.replace(\n\t\t\t/\\bcreate (unique )?index \"/gi,\n\t\t\t(_, unique = '') => `create ${unique}index if not exists \"`,\n\t\t)\n\t\t.replace(/\\badd column \"/gi, 'add column if not exists \"');\n}\n\n/** Headers a reverse proxy or CDN adds on the way in. */\nconst FORWARDING_HEADERS = [\n\t'forwarded',\n\t'x-forwarded-for',\n\t'x-forwarded-host',\n\t'x-real-ip',\n\t'cf-connecting-ip',\n\t'true-client-ip',\n\t'fastly-client-ip',\n\t'x-client-ip',\n];\n\n/**\n * `request`, without {@link CLIENT_IP_HEADER} unless an internal caller sent\n * it — no `Origin`, no forwarding header, a loopback or private peer: the\n * rule a request's span continues a trace by (`@geekmidas/telescope`'s\n * `isInternalCaller`).\n *\n * The stack's own edges strip the header already. This holds wherever one\n * does not — a platform's proxy, a port published straight to the internet —\n * so a stranger cannot pick the address Better Auth rate-limits them by.\n */\nexport function withTrustedClientIp(\n\trequest: Request,\n\tremoteAddress: string | undefined,\n): Request {\n\tif (!request.headers.has(CLIENT_IP_HEADER)) return request;\n\tconst internal =\n\t\t!request.headers.has('origin') &&\n\t\t!FORWARDING_HEADERS.some((name) => request.headers.has(name)) &&\n\t\tisPrivateAddress(remoteAddress);\n\tif (internal) return request;\n\n\tconst headers = new Headers(request.headers);\n\theaders.delete(CLIENT_IP_HEADER);\n\treturn new Request(request, { headers });\n}\n\n/** The TCP peer of a request served by `@hono/node-server`, when there is one. */\nfunction remoteAddressOf(c: { env: unknown }): string | undefined {\n\tconst env = c.env as\n\t\t| { incoming?: { socket?: { remoteAddress?: string } } }\n\t\t| undefined;\n\treturn env?.incoming?.socket?.remoteAddress;\n}\n\n/**\n * Whether `address` is loopback or private: 127/8, 10/8, 172.16/12,\n * 192.168/16, 169.254/16, `::1`, `fc00::/7`, `fe80::/10`, and an IPv4 one\n * mapped into IPv6.\n */\nfunction isPrivateAddress(address: string | undefined): boolean {\n\tif (!address) return false;\n\tconst ip = address.toLowerCase().replace(/^::ffff:/, '');\n\n\tconst v4 = ip.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n\tif (v4) {\n\t\tconst [a, b] = [Number(v4[1]), Number(v4[2])];\n\t\treturn (\n\t\t\ta === 127 ||\n\t\t\ta === 10 ||\n\t\t\t(a === 172 && b >= 16 && b <= 31) ||\n\t\t\t(a === 192 && b === 168) ||\n\t\t\t(a === 169 && b === 254)\n\t\t);\n\t}\n\n\tif (ip === '::1') return true;\n\treturn /^f[cd][0-9a-f]{2}:/.test(ip) || /^fe[89ab][0-9a-f]:/.test(ip);\n}\n"],"mappings":";;;;AA4KA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAKA;CA8BmB;CA7BlB;;;;;;;;;;;;CAYA;CACA;;;;;CAMA;CAQA,YACC,IACA,QACC;EADgB,KAAA,SAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,WAAW,OAAO,YAAY;EAInC,MAAM,WAAW,GAAG,UAAU;EAC9B,KAAK,OAAO;GACX;GACA,QAAQ,gBAAgB,QAAQ;GAChC,KAAK,WAAW,WAAW,KAAK;GAChC,gBAAgB,WAAW,WAAW,gBAAgB;GACtD,cAAc,WAAW,WAAW,cAAc;EACnD;EAGA,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,YAAY,KAAK,OAAO,QAAQ,SAAS;EACrD;CACD;;;;;;;;;;;;;;;CAgBA,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C;CAC/D,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,KAAK,QAAQ,YAAY,CAAC,CAAC,QAAQ,YAAY,EAAE;CAEvD,MAAM,KAAK,GAAG,MAAM,8CAA8C;CAClE,IAAI,IAAI;EACP,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,GAAG,EAAE,CAAC;EAC5C,OACC,MAAM,OACN,MAAM,MACL,MAAM,OAAO,KAAK,MAAM,KAAK,MAC7B,MAAM,OAAO,MAAM,OACnB,MAAM,OAAO,MAAM;CAEtB;CAEA,IAAI,OAAO,OAAO,OAAO;CACzB,OAAO,qBAAqB,KAAK,EAAE,KAAK,qBAAqB,KAAK,EAAE;AACrE"}
|
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { Construct } from "./construct-interface-
|
|
1
|
+
import { n as Construct } from "./construct-interface-DluK3_da.mjs";
|
|
2
2
|
import { ConstructName, Declaration } from "@geekmidas/manifest";
|
|
3
3
|
import { Cache } from "@geekmidas/cache";
|
|
4
4
|
import { Service } from "@geekmidas/services";
|
|
5
|
-
|
|
6
5
|
//#region src/cache.d.ts
|
|
7
|
-
|
|
8
6
|
interface CacheOptions {
|
|
9
7
|
/**
|
|
10
8
|
* The database this cache lives in.
|
|
@@ -41,7 +39,6 @@ declare class Cache$1<TName extends string = string> implements Construct<TName,
|
|
|
41
39
|
*/
|
|
42
40
|
private connect;
|
|
43
41
|
}
|
|
44
|
-
//# sourceMappingURL=cache.d.ts.map
|
|
45
42
|
//#endregion
|
|
46
|
-
export { Cache$1 as
|
|
47
|
-
//# sourceMappingURL=cache-
|
|
43
|
+
export { CacheOptions as n, Cache$1 as t };
|
|
44
|
+
//# sourceMappingURL=cache-CXh6GIgb.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-CXh6GIgb.d.mts","names":["Cache","CacheClient"],"sources":["../src/cache.ts"],"mappings":";;;;;UA6BiB;;;;;;;;EAQhB;;EAEA;;cAGYA,QAAM,0CACP,UAAU,OAAOC;mBAaV;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQA;;;;;mBAM9B;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAc3B,WAAW;;;;;;;;;;;;UAuBG"}
|
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { Construct } from "./construct-interface-
|
|
1
|
+
import { n as Construct } from "./construct-interface-B1AfqRl4.cjs";
|
|
2
2
|
import { Service } from "@geekmidas/services";
|
|
3
3
|
import { ConstructName, Declaration } from "@geekmidas/manifest";
|
|
4
4
|
import { Cache } from "@geekmidas/cache";
|
|
5
|
-
|
|
6
5
|
//#region src/cache.d.ts
|
|
7
|
-
|
|
8
6
|
interface CacheOptions {
|
|
9
7
|
/**
|
|
10
8
|
* The database this cache lives in.
|
|
@@ -41,7 +39,6 @@ declare class Cache$1<TName extends string = string> implements Construct<TName,
|
|
|
41
39
|
*/
|
|
42
40
|
private connect;
|
|
43
41
|
}
|
|
44
|
-
//# sourceMappingURL=cache.d.ts.map
|
|
45
42
|
//#endregion
|
|
46
|
-
export { Cache$1 as
|
|
47
|
-
//# sourceMappingURL=cache-
|
|
43
|
+
export { CacheOptions as n, Cache$1 as t };
|
|
44
|
+
//# sourceMappingURL=cache-DnGDGly3.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-DnGDGly3.d.cts","names":["Cache","CacheClient"],"sources":["../src/cache.ts"],"mappings":";;;;;UA6BiB;;;;;;;;EAQhB;;EAEA;;cAGYA,QAAM,0CACP,UAAU,OAAOC;mBAaV;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQA;;;;;mBAM9B;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAc3B,WAAW;;;;;;;;;;;;UAuBG"}
|
package/dist/cache.cjs
CHANGED
|
@@ -1,3 +1,69 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
3
|
+
let _geekmidas_cache = require("@geekmidas/cache");
|
|
4
|
+
//#region src/cache.ts
|
|
5
|
+
/**
|
|
6
|
+
* `Cache` — a declared key/value cache.
|
|
7
|
+
*
|
|
8
|
+
* The same three-package meeting point as `ObjectStorage` and `Email`: it
|
|
9
|
+
* implements the construct contract, derives its env key through
|
|
10
|
+
* `@geekmidas/manifest`, and hands back a `@geekmidas/cache` client.
|
|
11
|
+
*
|
|
12
|
+
* It names no provider — and unlike `Email`, it cannot name one protocol
|
|
13
|
+
* either. Every mail backend speaks SMTP, so an `smtp://` URL is true of all of
|
|
14
|
+
* them; cache backends genuinely differ, because Upstash speaks HTTP, a Redis
|
|
15
|
+
* speaks its wire protocol, and a table in Postgres speaks SQL. So the scheme in
|
|
16
|
+
* the URL picks the driver, exactly as it does for object storage, and which
|
|
17
|
+
* drivers exist is the generated entry point's decision.
|
|
18
|
+
*
|
|
19
|
+
* The backend is chosen at deploy, not here. An app caching in Postgres and an
|
|
20
|
+
* app caching in Upstash are the same application code.
|
|
21
|
+
*/
|
|
22
|
+
var Cache = class {
|
|
23
|
+
options;
|
|
24
|
+
id;
|
|
25
|
+
service;
|
|
26
|
+
/**
|
|
27
|
+
* Declared once and read by both `declare()` and `connect()`, so the key the
|
|
28
|
+
* target publishes and the key the client reads cannot drift.
|
|
29
|
+
*/
|
|
30
|
+
key;
|
|
31
|
+
constructor(id, options = {}) {
|
|
32
|
+
this.options = options;
|
|
33
|
+
const canonical = (0, _geekmidas_manifest.canonicalId)(id);
|
|
34
|
+
this.id = canonical;
|
|
35
|
+
this.key = (0, _geekmidas_manifest.provideKey)(canonical, "url");
|
|
36
|
+
this.service = {
|
|
37
|
+
serviceName: (0, _geekmidas_manifest.serviceKey)(canonical),
|
|
38
|
+
register: (options) => this.connect(options)
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
declare() {
|
|
42
|
+
return [{
|
|
43
|
+
kind: "cache",
|
|
44
|
+
id: this.id,
|
|
45
|
+
...this.options.of ? { of: this.options.of } : {},
|
|
46
|
+
...this.options.table ? { table: this.options.table } : {},
|
|
47
|
+
provides: [this.key]
|
|
48
|
+
}];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Builds the client from the single URL the target supplied.
|
|
52
|
+
*
|
|
53
|
+
* Any credential travels in that URL's userinfo rather than in a second key,
|
|
54
|
+
* for the same reason a Postgres password does: an address and the thing that
|
|
55
|
+
* opens it are one fact, and splitting them is one more thing to keep in step.
|
|
56
|
+
*
|
|
57
|
+
* The scheme selects the driver, so this construct imports no provider and
|
|
58
|
+
* an app that caches in Postgres never resolves a Redis client. Whoever
|
|
59
|
+
* assembles the application registers the drivers its target needs.
|
|
60
|
+
*/
|
|
61
|
+
async connect({ envParser }) {
|
|
62
|
+
const { url } = envParser.create((get) => ({ url: get(this.key).string() })).parse();
|
|
63
|
+
return (0, _geekmidas_cache.createCacheClient)(url);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
//#endregion
|
|
67
|
+
exports.Cache = Cache;
|
|
2
68
|
|
|
3
|
-
|
|
69
|
+
//# sourceMappingURL=cache.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.cjs","names":["canonicalId","provideKey","serviceKey","createCacheClient"],"sources":["../src/cache.ts"],"sourcesContent":["/**\n * `Cache` — a declared key/value cache.\n *\n * The same three-package meeting point as `ObjectStorage` and `Email`: it\n * implements the construct contract, derives its env key through\n * `@geekmidas/manifest`, and hands back a `@geekmidas/cache` client.\n *\n * It names no provider — and unlike `Email`, it cannot name one protocol\n * either. Every mail backend speaks SMTP, so an `smtp://` URL is true of all of\n * them; cache backends genuinely differ, because Upstash speaks HTTP, a Redis\n * speaks its wire protocol, and a table in Postgres speaks SQL. So the scheme in\n * the URL picks the driver, exactly as it does for object storage, and which\n * drivers exist is the generated entry point's decision.\n *\n * The backend is chosen at deploy, not here. An app caching in Postgres and an\n * app caching in Upstash are the same application code.\n */\n\nimport { type Cache as CacheClient, createCacheClient } from '@geekmidas/cache';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { Construct } from './construct-interface';\n\nexport interface CacheOptions {\n\t/**\n\t * The database this cache lives in.\n\t *\n\t * Set by `database.cache()` rather than written by hand — the point of the\n\t * method is that the parent's id comes from the parent rather than from a\n\t * string somebody has to keep in step.\n\t */\n\tof?: string;\n\t/** The table entries are kept in. Defaults to `cache`. */\n\ttable?: string;\n}\n\nexport class Cache<TName extends string = string>\n\timplements Construct<TName, CacheClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, CacheClient>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * target publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly key: string;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: CacheOptions = {},\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.key = provideKey(canonical, 'url');\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'cache',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.options.of ? { of: this.options.of } : {}),\n\t\t\t\t...(this.options.table ? { table: this.options.table } : {}),\n\t\t\t\tprovides: [this.key],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Builds the client from the single URL the target supplied.\n\t *\n\t * Any credential travels in that URL's userinfo rather than in a second key,\n\t * for the same reason a Postgres password does: an address and the thing that\n\t * opens it are one fact, and splitting them is one more thing to keep in step.\n\t *\n\t * The scheme selects the driver, so this construct imports no provider and\n\t * an app that caches in Postgres never resolves a Redis client. Whoever\n\t * assembles the application registers the drivers its target needs.\n\t */\n\tprivate async connect({\n\t\tenvParser,\n\t}: ServiceRegisterOptions): Promise<CacheClient> {\n\t\tconst { url } = envParser\n\t\t\t.create((get) => ({ url: get(this.key).string() }))\n\t\t\t.parse();\n\n\t\treturn createCacheClient(url);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0CA,IAAa,QAAb,MAEA;CAYmB;CAXlB;CACA;;;;;CAMA;CAEA,YACC,IACA,UAAyC,CAAC,GACzC;EADgB,KAAA,UAAA;EAEjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,OAAA,GAAMC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;EAGtC,KAAK,UAAU;GACd,cAAA,GAAaC,oBAAAA,WAAAA,CAAW,SAAS;GACjC,WAAW,YAAY,KAAK,QAAQ,OAAO;EAC5C;CACD;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,GAAI,KAAK,QAAQ,KAAK,EAAE,IAAI,KAAK,QAAQ,GAAG,IAAI,CAAC;GACjD,GAAI,KAAK,QAAQ,QAAQ,EAAE,OAAO,KAAK,QAAQ,MAAM,IAAI,CAAC;GAC1D,UAAU,CAAC,KAAK,GAAG;EACpB,CACD;CACD;;;;;;;;;;;;CAaA,MAAc,QAAQ,EACrB,aACgD;EAChD,MAAM,EAAE,QAAQ,UACd,QAAQ,SAAS,EAAE,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAClD,MAAM;EAER,QAAA,GAAOC,iBAAAA,kBAAAA,CAAkB,GAAG;CAC7B;AACD"}
|
package/dist/cache.d.cts
CHANGED
package/dist/cache.d.mts
CHANGED
package/dist/cache.mjs
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { canonicalId, provideKey, serviceKey } from "@geekmidas/manifest";
|
|
2
|
+
import { createCacheClient } from "@geekmidas/cache";
|
|
3
|
+
//#region src/cache.ts
|
|
4
|
+
/**
|
|
5
|
+
* `Cache` — a declared key/value cache.
|
|
6
|
+
*
|
|
7
|
+
* The same three-package meeting point as `ObjectStorage` and `Email`: it
|
|
8
|
+
* implements the construct contract, derives its env key through
|
|
9
|
+
* `@geekmidas/manifest`, and hands back a `@geekmidas/cache` client.
|
|
10
|
+
*
|
|
11
|
+
* It names no provider — and unlike `Email`, it cannot name one protocol
|
|
12
|
+
* either. Every mail backend speaks SMTP, so an `smtp://` URL is true of all of
|
|
13
|
+
* them; cache backends genuinely differ, because Upstash speaks HTTP, a Redis
|
|
14
|
+
* speaks its wire protocol, and a table in Postgres speaks SQL. So the scheme in
|
|
15
|
+
* the URL picks the driver, exactly as it does for object storage, and which
|
|
16
|
+
* drivers exist is the generated entry point's decision.
|
|
17
|
+
*
|
|
18
|
+
* The backend is chosen at deploy, not here. An app caching in Postgres and an
|
|
19
|
+
* app caching in Upstash are the same application code.
|
|
20
|
+
*/
|
|
21
|
+
var Cache = class {
|
|
22
|
+
options;
|
|
23
|
+
id;
|
|
24
|
+
service;
|
|
25
|
+
/**
|
|
26
|
+
* Declared once and read by both `declare()` and `connect()`, so the key the
|
|
27
|
+
* target publishes and the key the client reads cannot drift.
|
|
28
|
+
*/
|
|
29
|
+
key;
|
|
30
|
+
constructor(id, options = {}) {
|
|
31
|
+
this.options = options;
|
|
32
|
+
const canonical = canonicalId(id);
|
|
33
|
+
this.id = canonical;
|
|
34
|
+
this.key = provideKey(canonical, "url");
|
|
35
|
+
this.service = {
|
|
36
|
+
serviceName: serviceKey(canonical),
|
|
37
|
+
register: (options) => this.connect(options)
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
declare() {
|
|
41
|
+
return [{
|
|
42
|
+
kind: "cache",
|
|
43
|
+
id: this.id,
|
|
44
|
+
...this.options.of ? { of: this.options.of } : {},
|
|
45
|
+
...this.options.table ? { table: this.options.table } : {},
|
|
46
|
+
provides: [this.key]
|
|
47
|
+
}];
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Builds the client from the single URL the target supplied.
|
|
51
|
+
*
|
|
52
|
+
* Any credential travels in that URL's userinfo rather than in a second key,
|
|
53
|
+
* for the same reason a Postgres password does: an address and the thing that
|
|
54
|
+
* opens it are one fact, and splitting them is one more thing to keep in step.
|
|
55
|
+
*
|
|
56
|
+
* The scheme selects the driver, so this construct imports no provider and
|
|
57
|
+
* an app that caches in Postgres never resolves a Redis client. Whoever
|
|
58
|
+
* assembles the application registers the drivers its target needs.
|
|
59
|
+
*/
|
|
60
|
+
async connect({ envParser }) {
|
|
61
|
+
const { url } = envParser.create((get) => ({ url: get(this.key).string() })).parse();
|
|
62
|
+
return createCacheClient(url);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
//#endregion
|
|
66
|
+
export { Cache };
|
|
2
67
|
|
|
3
|
-
|
|
68
|
+
//# sourceMappingURL=cache.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.mjs","names":[],"sources":["../src/cache.ts"],"sourcesContent":["/**\n * `Cache` — a declared key/value cache.\n *\n * The same three-package meeting point as `ObjectStorage` and `Email`: it\n * implements the construct contract, derives its env key through\n * `@geekmidas/manifest`, and hands back a `@geekmidas/cache` client.\n *\n * It names no provider — and unlike `Email`, it cannot name one protocol\n * either. Every mail backend speaks SMTP, so an `smtp://` URL is true of all of\n * them; cache backends genuinely differ, because Upstash speaks HTTP, a Redis\n * speaks its wire protocol, and a table in Postgres speaks SQL. So the scheme in\n * the URL picks the driver, exactly as it does for object storage, and which\n * drivers exist is the generated entry point's decision.\n *\n * The backend is chosen at deploy, not here. An app caching in Postgres and an\n * app caching in Upstash are the same application code.\n */\n\nimport { type Cache as CacheClient, createCacheClient } from '@geekmidas/cache';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { Construct } from './construct-interface';\n\nexport interface CacheOptions {\n\t/**\n\t * The database this cache lives in.\n\t *\n\t * Set by `database.cache()` rather than written by hand — the point of the\n\t * method is that the parent's id comes from the parent rather than from a\n\t * string somebody has to keep in step.\n\t */\n\tof?: string;\n\t/** The table entries are kept in. Defaults to `cache`. */\n\ttable?: string;\n}\n\nexport class Cache<TName extends string = string>\n\timplements Construct<TName, CacheClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, CacheClient>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * target publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly key: string;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: CacheOptions = {},\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.key = provideKey(canonical, 'url');\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'cache',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.options.of ? { of: this.options.of } : {}),\n\t\t\t\t...(this.options.table ? { table: this.options.table } : {}),\n\t\t\t\tprovides: [this.key],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Builds the client from the single URL the target supplied.\n\t *\n\t * Any credential travels in that URL's userinfo rather than in a second key,\n\t * for the same reason a Postgres password does: an address and the thing that\n\t * opens it are one fact, and splitting them is one more thing to keep in step.\n\t *\n\t * The scheme selects the driver, so this construct imports no provider and\n\t * an app that caches in Postgres never resolves a Redis client. Whoever\n\t * assembles the application registers the drivers its target needs.\n\t */\n\tprivate async connect({\n\t\tenvParser,\n\t}: ServiceRegisterOptions): Promise<CacheClient> {\n\t\tconst { url } = envParser\n\t\t\t.create((get) => ({ url: get(this.key).string() }))\n\t\t\t.parse();\n\n\t\treturn createCacheClient(url);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0CA,IAAa,QAAb,MAEA;CAYmB;CAXlB;CACA;;;;;CAMA;CAEA,YACC,IACA,UAAyC,CAAC,GACzC;EADgB,KAAA,UAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,MAAM,WAAW,WAAW,KAAK;EAGtC,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,YAAY,KAAK,QAAQ,OAAO;EAC5C;CACD;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,GAAI,KAAK,QAAQ,KAAK,EAAE,IAAI,KAAK,QAAQ,GAAG,IAAI,CAAC;GACjD,GAAI,KAAK,QAAQ,QAAQ,EAAE,OAAO,KAAK,QAAQ,MAAM,IAAI,CAAC;GAC1D,UAAU,CAAC,KAAK,GAAG;EACpB,CACD;CACD;;;;;;;;;;;;CAaA,MAAc,QAAQ,EACrB,aACgD;EAChD,MAAM,EAAE,QAAQ,UACd,QAAQ,SAAS,EAAE,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAClD,MAAM;EAER,OAAO,kBAAkB,GAAG;CAC7B;AACD"}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "node:crypto";
|
|
2
|
+
//#region src/encryption/cipher.ts
|
|
3
|
+
/**
|
|
4
|
+
* The cipher behind an `Encryption` construct, and the format it writes.
|
|
5
|
+
*
|
|
6
|
+
* Every ciphertext names the key that wrote it — `gkm1.<keyId>.<payload>` — so
|
|
7
|
+
* `decrypt` never has to guess, a rotated key still opens what it wrote, and
|
|
8
|
+
* retiring a key is a decision made against data rather than a hope. The
|
|
9
|
+
* format version leads, so the day it has to change, both can be read.
|
|
10
|
+
*
|
|
11
|
+
* Two backends, picked by the scheme of the construct's URL, the way a queue's
|
|
12
|
+
* connection string picks its broker:
|
|
13
|
+
*
|
|
14
|
+
* - `aes256gcm://` — a keyring this process holds: AES-256-GCM with the newest
|
|
15
|
+
* key, HMAC-SHA256 for the blind index. Local, test and server stages.
|
|
16
|
+
* - `kms://` — envelope encryption under an AWS KMS key, and a KMS HMAC key for
|
|
17
|
+
* the index. The key material never leaves KMS. See `./kms`.
|
|
18
|
+
*/
|
|
19
|
+
/** The format every ciphertext leads with. */
|
|
20
|
+
const CIPHERTEXT_VERSION = "gkm1";
|
|
21
|
+
/** AES-256-GCM's nonce and tag, in bytes. */
|
|
22
|
+
const IV_BYTES = 12;
|
|
23
|
+
const KEY_BYTES = 32;
|
|
24
|
+
const LOCAL_SCHEME = "aes256gcm:";
|
|
25
|
+
var EncryptionUrlInvalid = class extends Error {
|
|
26
|
+
construct;
|
|
27
|
+
reason;
|
|
28
|
+
constructor(construct, reason) {
|
|
29
|
+
super(`${construct}'s encryption URL is not usable: ${reason}. gkm composes it — derived locally, generated into a server stage's secrets on its first deploy, provisioned on AWS — so it should not be set by hand.`);
|
|
30
|
+
this.construct = construct;
|
|
31
|
+
this.reason = reason;
|
|
32
|
+
this.name = "EncryptionUrlInvalid";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var UnknownEncryptionScheme = class extends Error {
|
|
36
|
+
construct;
|
|
37
|
+
scheme;
|
|
38
|
+
constructor(construct, scheme) {
|
|
39
|
+
super(`${construct}'s encryption URL uses '${scheme}', which no cipher handles. Expected 'aes256gcm:' (a local keyring) or 'kms:' (AWS KMS).`);
|
|
40
|
+
this.construct = construct;
|
|
41
|
+
this.scheme = scheme;
|
|
42
|
+
this.name = "UnknownEncryptionScheme";
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var CiphertextMalformed = class extends Error {
|
|
46
|
+
construct;
|
|
47
|
+
constructor(construct) {
|
|
48
|
+
super(`${construct} was asked to decrypt something it did not write: a ciphertext starts '${CIPHERTEXT_VERSION}.<key>.'. Check the column holds what \`encrypt\` returned, untrimmed.`);
|
|
49
|
+
this.construct = construct;
|
|
50
|
+
this.name = "CiphertextMalformed";
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
var EncryptionKeyRetired = class extends Error {
|
|
54
|
+
construct;
|
|
55
|
+
keyId;
|
|
56
|
+
constructor(construct, keyId) {
|
|
57
|
+
super(`${construct} has no key '${keyId}' any more, so a value it wrote cannot be read. It was retired before every value was re-encrypted; restore it from the stage's secrets history, run the sweep, then retire it again.`);
|
|
58
|
+
this.construct = construct;
|
|
59
|
+
this.keyId = keyId;
|
|
60
|
+
this.name = "EncryptionKeyRetired";
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
var CiphertextNotAuthentic = class extends Error {
|
|
64
|
+
construct;
|
|
65
|
+
constructor(construct) {
|
|
66
|
+
super(`${construct} could not authenticate a ciphertext: it was altered, or written by a different Encryption construct. Ciphertexts are bound to the construct that wrote them.`);
|
|
67
|
+
this.construct = construct;
|
|
68
|
+
this.name = "CiphertextNotAuthentic";
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var CurrentKeyCannotRetire = class extends Error {
|
|
72
|
+
construct;
|
|
73
|
+
keyId;
|
|
74
|
+
constructor(construct, keyId) {
|
|
75
|
+
super(`'${keyId}' is ${construct}'s current key — everything new is written with it. Rotate first, sweep, then retire '${keyId}'.`);
|
|
76
|
+
this.construct = construct;
|
|
77
|
+
this.keyId = keyId;
|
|
78
|
+
this.name = "CurrentKeyCannotRetire";
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
/** A ciphertext's three parts. */
|
|
82
|
+
function parseCiphertext(construct, ciphertext) {
|
|
83
|
+
const [version, keyId, payload, ...rest] = ciphertext.split(".");
|
|
84
|
+
if (version !== "gkm1" || !keyId || !payload || rest.length) throw new CiphertextMalformed(construct);
|
|
85
|
+
return {
|
|
86
|
+
keyId,
|
|
87
|
+
payload: Buffer.from(payload, "base64url")
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function formatCiphertext(keyId, payload) {
|
|
91
|
+
return `${CIPHERTEXT_VERSION}.${keyId}.${payload.toString("base64url")}`;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* What the cipher authenticates alongside the data: the construct and the key.
|
|
95
|
+
*
|
|
96
|
+
* Binding the construct means a value copied from one `Encryption` into
|
|
97
|
+
* another's column fails instead of decrypting under the wrong policy.
|
|
98
|
+
*/
|
|
99
|
+
function associatedData(construct, keyId) {
|
|
100
|
+
return Buffer.from(`${CIPHERTEXT_VERSION}:${construct}:${keyId}`);
|
|
101
|
+
}
|
|
102
|
+
/** `iv | tag | ciphertext`, under one AES-256-GCM key. */
|
|
103
|
+
function seal(key, plaintext, aad) {
|
|
104
|
+
const iv = randomBytes(IV_BYTES);
|
|
105
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
106
|
+
cipher.setAAD(aad);
|
|
107
|
+
const body = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
108
|
+
return Buffer.concat([
|
|
109
|
+
iv,
|
|
110
|
+
cipher.getAuthTag(),
|
|
111
|
+
body
|
|
112
|
+
]);
|
|
113
|
+
}
|
|
114
|
+
/** The inverse of {@link seal}; `undefined` when it does not authenticate. */
|
|
115
|
+
function open(key, sealed, aad) {
|
|
116
|
+
if (sealed.length < 28) return void 0;
|
|
117
|
+
const decipher = createDecipheriv("aes-256-gcm", key, sealed.subarray(0, IV_BYTES));
|
|
118
|
+
decipher.setAAD(aad);
|
|
119
|
+
decipher.setAuthTag(sealed.subarray(IV_BYTES, 28));
|
|
120
|
+
try {
|
|
121
|
+
return Buffer.concat([decipher.update(sealed.subarray(28)), decipher.final()]);
|
|
122
|
+
} catch {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** Parse `aes256gcm://local?keys=k2.<key>,k1.<key>&index=<key>`. */
|
|
127
|
+
function parseKeyring(construct, url) {
|
|
128
|
+
let parsed;
|
|
129
|
+
try {
|
|
130
|
+
parsed = new URL(url);
|
|
131
|
+
} catch {
|
|
132
|
+
throw new EncryptionUrlInvalid(construct, "it is not a URL");
|
|
133
|
+
}
|
|
134
|
+
const keys = (parsed.searchParams.get("keys") ?? "").split(",").filter(Boolean).map((entry) => {
|
|
135
|
+
const [id, encoded] = entry.split(".");
|
|
136
|
+
const key = Buffer.from(encoded ?? "", "base64url");
|
|
137
|
+
if (!id || key.length !== KEY_BYTES) throw new EncryptionUrlInvalid(construct, `'${id ?? entry}' is not a 256-bit key`);
|
|
138
|
+
return {
|
|
139
|
+
id,
|
|
140
|
+
key
|
|
141
|
+
};
|
|
142
|
+
});
|
|
143
|
+
if (keys.length === 0) throw new EncryptionUrlInvalid(construct, "it holds no keys");
|
|
144
|
+
const index = Buffer.from(parsed.searchParams.get("index") ?? "", "base64url");
|
|
145
|
+
if (index.length !== KEY_BYTES) throw new EncryptionUrlInvalid(construct, "its index key is missing");
|
|
146
|
+
return {
|
|
147
|
+
keys,
|
|
148
|
+
index
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function formatKeyring(keyring) {
|
|
152
|
+
const keys = keyring.keys.map(({ id, key }) => `${id}.${key.toString("base64url")}`).join(",");
|
|
153
|
+
return `${LOCAL_SCHEME}//local?keys=${keys}&index=${keyring.index.toString("base64url")}`;
|
|
154
|
+
}
|
|
155
|
+
/** A keyring with one fresh key, `k1`, and a fresh index key. */
|
|
156
|
+
function generateKeyring() {
|
|
157
|
+
return formatKeyring({
|
|
158
|
+
keys: [{
|
|
159
|
+
id: "k1",
|
|
160
|
+
key: randomBytes(KEY_BYTES)
|
|
161
|
+
}],
|
|
162
|
+
index: randomBytes(KEY_BYTES)
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The keyring with a new current key in front, and every older one kept.
|
|
167
|
+
*
|
|
168
|
+
* Nothing is dropped: what the old keys wrote still has to open until a sweep
|
|
169
|
+
* has re-encrypted it — see {@link retireKey}.
|
|
170
|
+
*/
|
|
171
|
+
function rotateKeyring(construct, url) {
|
|
172
|
+
const keyring = parseKeyring(construct, url);
|
|
173
|
+
const next = Math.max(...keyring.keys.map(({ id }) => Number(id.slice(1)) || 0)) + 1;
|
|
174
|
+
return formatKeyring({
|
|
175
|
+
...keyring,
|
|
176
|
+
keys: [{
|
|
177
|
+
id: `k${next}`,
|
|
178
|
+
key: randomBytes(KEY_BYTES)
|
|
179
|
+
}, ...keyring.keys]
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
/** The keyring without `keyId`, which must not be the current key. */
|
|
183
|
+
function retireKey(construct, url, keyId) {
|
|
184
|
+
const keyring = parseKeyring(construct, url);
|
|
185
|
+
if (keyring.keys[0]?.id === keyId) throw new CurrentKeyCannotRetire(construct, keyId);
|
|
186
|
+
if (!keyring.keys.some(({ id }) => id === keyId)) throw new EncryptionKeyRetired(construct, keyId);
|
|
187
|
+
return formatKeyring({
|
|
188
|
+
...keyring,
|
|
189
|
+
keys: keyring.keys.filter(({ id }) => id !== keyId)
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/** The `aes256gcm://` cipher: a keyring held in process. */
|
|
193
|
+
function keyringCipher(construct, url, onStaleKey = () => {}) {
|
|
194
|
+
const keyring = parseKeyring(construct, url);
|
|
195
|
+
const current = keyring.keys[0];
|
|
196
|
+
const byId = new Map(keyring.keys.map(({ id, key }) => [id, key]));
|
|
197
|
+
const reported = /* @__PURE__ */ new Set();
|
|
198
|
+
const decrypt = async (ciphertext) => {
|
|
199
|
+
const { keyId, payload } = parseCiphertext(construct, ciphertext);
|
|
200
|
+
const key = byId.get(keyId);
|
|
201
|
+
if (!key) throw new EncryptionKeyRetired(construct, keyId);
|
|
202
|
+
const plaintext = open(key, payload, associatedData(construct, keyId));
|
|
203
|
+
if (!plaintext) throw new CiphertextNotAuthentic(construct);
|
|
204
|
+
if (keyId !== current.id && !reported.has(keyId)) {
|
|
205
|
+
reported.add(keyId);
|
|
206
|
+
onStaleKey(keyId, current.id);
|
|
207
|
+
}
|
|
208
|
+
return plaintext.toString("utf8");
|
|
209
|
+
};
|
|
210
|
+
const encrypt = async (plaintext) => formatCiphertext(current.id, seal(current.key, Buffer.from(plaintext, "utf8"), associatedData(construct, current.id)));
|
|
211
|
+
return {
|
|
212
|
+
encrypt,
|
|
213
|
+
decrypt,
|
|
214
|
+
index: async (value) => createHmac("sha256", keyring.index).update(value, "utf8").digest("base64url"),
|
|
215
|
+
reencrypt: async (ciphertext) => {
|
|
216
|
+
const { keyId } = parseCiphertext(construct, ciphertext);
|
|
217
|
+
if (keyId === current.id) return ciphertext;
|
|
218
|
+
return encrypt(await decrypt(ciphertext));
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
//#endregion
|
|
223
|
+
export { rotateKeyring as _, EncryptionUrlInvalid as a, associatedData as c, generateKeyring as d, keyringCipher as f, retireKey as g, parseKeyring as h, EncryptionKeyRetired as i, formatCiphertext as l, parseCiphertext as m, CiphertextNotAuthentic as n, LOCAL_SCHEME as o, open as p, CurrentKeyCannotRetire as r, UnknownEncryptionScheme as s, CiphertextMalformed as t, formatKeyring as u, seal as v };
|
|
224
|
+
|
|
225
|
+
//# sourceMappingURL=cipher-C1lEFX63.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cipher-C1lEFX63.mjs","names":[],"sources":["../src/encryption/cipher.ts"],"sourcesContent":["/**\n * The cipher behind an `Encryption` construct, and the format it writes.\n *\n * Every ciphertext names the key that wrote it — `gkm1.<keyId>.<payload>` — so\n * `decrypt` never has to guess, a rotated key still opens what it wrote, and\n * retiring a key is a decision made against data rather than a hope. The\n * format version leads, so the day it has to change, both can be read.\n *\n * Two backends, picked by the scheme of the construct's URL, the way a queue's\n * connection string picks its broker:\n *\n * - `aes256gcm://` — a keyring this process holds: AES-256-GCM with the newest\n * key, HMAC-SHA256 for the blind index. Local, test and server stages.\n * - `kms://` — envelope encryption under an AWS KMS key, and a KMS HMAC key for\n * the index. The key material never leaves KMS. See `./kms`.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHmac,\n\trandomBytes,\n} from 'node:crypto';\n\n/** What a handler is given: `services.pii.encrypt(…)` and the rest. */\nexport interface Cipher {\n\t/** Plaintext in, a self-describing ciphertext string out. */\n\tencrypt(plaintext: string): Promise<string>;\n\t/** Opens any ciphertext this construct wrote, under whichever key wrote it. */\n\tdecrypt(ciphertext: string): Promise<string>;\n\t/**\n\t * A blind index: the same value always gives the same string, so an\n\t * encrypted column can still be looked up by an indexed column beside it.\n\t *\n\t * Deterministic on purpose, which is also why its key never rotates — a\n\t * rotated index key would make every stored index miss.\n\t */\n\tindex(value: string): Promise<string>;\n\t/**\n\t * The same plaintext under the current key — what a sweep runs over a\n\t * column before an old key is retired. Unchanged when it is already current.\n\t */\n\treencrypt(ciphertext: string): Promise<string>;\n}\n\n/** The format every ciphertext leads with. */\nexport const CIPHERTEXT_VERSION = 'gkm1';\n\n/** AES-256-GCM's nonce and tag, in bytes. */\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\n\nexport const LOCAL_SCHEME = 'aes256gcm:';\n\nexport class EncryptionUrlInvalid extends Error {\n\tconstructor(\n\t\treadonly construct: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`${construct}'s encryption URL is not usable: ${reason}. gkm composes it — derived locally, generated into a server stage's secrets on its first deploy, provisioned on AWS — so it should not be set by hand.`,\n\t\t);\n\t\tthis.name = 'EncryptionUrlInvalid';\n\t}\n}\n\nexport class UnknownEncryptionScheme extends Error {\n\tconstructor(\n\t\treadonly construct: string,\n\t\treadonly scheme: string,\n\t) {\n\t\tsuper(\n\t\t\t`${construct}'s encryption URL uses '${scheme}', which no cipher handles. Expected 'aes256gcm:' (a local keyring) or 'kms:' (AWS KMS).`,\n\t\t);\n\t\tthis.name = 'UnknownEncryptionScheme';\n\t}\n}\n\nexport class CiphertextMalformed extends Error {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`${construct} was asked to decrypt something it did not write: a ciphertext starts '${CIPHERTEXT_VERSION}.<key>.'. Check the column holds what \\`encrypt\\` returned, untrimmed.`,\n\t\t);\n\t\tthis.name = 'CiphertextMalformed';\n\t}\n}\n\nexport class EncryptionKeyRetired extends Error {\n\tconstructor(\n\t\treadonly construct: string,\n\t\treadonly keyId: string,\n\t) {\n\t\tsuper(\n\t\t\t`${construct} has no key '${keyId}' any more, so a value it wrote cannot be read. It was retired before every value was re-encrypted; restore it from the stage's secrets history, run the sweep, then retire it again.`,\n\t\t);\n\t\tthis.name = 'EncryptionKeyRetired';\n\t}\n}\n\nexport class CiphertextNotAuthentic extends Error {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`${construct} could not authenticate a ciphertext: it was altered, or written by a different Encryption construct. Ciphertexts are bound to the construct that wrote them.`,\n\t\t);\n\t\tthis.name = 'CiphertextNotAuthentic';\n\t}\n}\n\nexport class CurrentKeyCannotRetire extends Error {\n\tconstructor(\n\t\treadonly construct: string,\n\t\treadonly keyId: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${keyId}' is ${construct}'s current key — everything new is written with it. Rotate first, sweep, then retire '${keyId}'.`,\n\t\t);\n\t\tthis.name = 'CurrentKeyCannotRetire';\n\t}\n}\n\n/** A ciphertext's three parts. */\nexport function parseCiphertext(\n\tconstruct: string,\n\tciphertext: string,\n): { keyId: string; payload: Buffer } {\n\tconst [version, keyId, payload, ...rest] = ciphertext.split('.');\n\tif (version !== CIPHERTEXT_VERSION || !keyId || !payload || rest.length) {\n\t\tthrow new CiphertextMalformed(construct);\n\t}\n\treturn { keyId, payload: Buffer.from(payload, 'base64url') };\n}\n\nexport function formatCiphertext(keyId: string, payload: Buffer): string {\n\treturn `${CIPHERTEXT_VERSION}.${keyId}.${payload.toString('base64url')}`;\n}\n\n/**\n * What the cipher authenticates alongside the data: the construct and the key.\n *\n * Binding the construct means a value copied from one `Encryption` into\n * another's column fails instead of decrypting under the wrong policy.\n */\nexport function associatedData(construct: string, keyId: string): Buffer {\n\treturn Buffer.from(`${CIPHERTEXT_VERSION}:${construct}:${keyId}`);\n}\n\n/** `iv | tag | ciphertext`, under one AES-256-GCM key. */\nexport function seal(key: Buffer, plaintext: Buffer, aad: Buffer): Buffer {\n\tconst iv = randomBytes(IV_BYTES);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tcipher.setAAD(aad);\n\tconst body = Buffer.concat([cipher.update(plaintext), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]);\n}\n\n/** The inverse of {@link seal}; `undefined` when it does not authenticate. */\nexport function open(\n\tkey: Buffer,\n\tsealed: Buffer,\n\taad: Buffer,\n): Buffer | undefined {\n\tif (sealed.length < IV_BYTES + TAG_BYTES) return undefined;\n\n\tconst decipher = createDecipheriv(\n\t\t'aes-256-gcm',\n\t\tkey,\n\t\tsealed.subarray(0, IV_BYTES),\n\t);\n\tdecipher.setAAD(aad);\n\tdecipher.setAuthTag(sealed.subarray(IV_BYTES, IV_BYTES + TAG_BYTES));\n\n\ttry {\n\t\treturn Buffer.concat([\n\t\t\tdecipher.update(sealed.subarray(IV_BYTES + TAG_BYTES)),\n\t\t\tdecipher.final(),\n\t\t]);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** A local keyring: newest key first, and the index key that never rotates. */\nexport interface Keyring {\n\tkeys: { id: string; key: Buffer }[];\n\tindex: Buffer;\n}\n\n/** Parse `aes256gcm://local?keys=k2.<key>,k1.<key>&index=<key>`. */\nexport function parseKeyring(construct: string, url: string): Keyring {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\tthrow new EncryptionUrlInvalid(construct, 'it is not a URL');\n\t}\n\n\tconst keys = (parsed.searchParams.get('keys') ?? '')\n\t\t.split(',')\n\t\t.filter(Boolean)\n\t\t.map((entry) => {\n\t\t\tconst [id, encoded] = entry.split('.');\n\t\t\tconst key = Buffer.from(encoded ?? '', 'base64url');\n\t\t\tif (!id || key.length !== KEY_BYTES) {\n\t\t\t\tthrow new EncryptionUrlInvalid(\n\t\t\t\t\tconstruct,\n\t\t\t\t\t`'${id ?? entry}' is not a 256-bit key`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { id, key };\n\t\t});\n\tif (keys.length === 0) {\n\t\tthrow new EncryptionUrlInvalid(construct, 'it holds no keys');\n\t}\n\n\tconst index = Buffer.from(\n\t\tparsed.searchParams.get('index') ?? '',\n\t\t'base64url',\n\t);\n\tif (index.length !== KEY_BYTES) {\n\t\tthrow new EncryptionUrlInvalid(construct, 'its index key is missing');\n\t}\n\n\treturn { keys, index };\n}\n\nexport function formatKeyring(keyring: Keyring): string {\n\tconst keys = keyring.keys\n\t\t.map(({ id, key }) => `${id}.${key.toString('base64url')}`)\n\t\t.join(',');\n\treturn `${LOCAL_SCHEME}//local?keys=${keys}&index=${keyring.index.toString('base64url')}`;\n}\n\n/** A keyring with one fresh key, `k1`, and a fresh index key. */\nexport function generateKeyring(): string {\n\treturn formatKeyring({\n\t\tkeys: [{ id: 'k1', key: randomBytes(KEY_BYTES) }],\n\t\tindex: randomBytes(KEY_BYTES),\n\t});\n}\n\n/**\n * The keyring with a new current key in front, and every older one kept.\n *\n * Nothing is dropped: what the old keys wrote still has to open until a sweep\n * has re-encrypted it — see {@link retireKey}.\n */\nexport function rotateKeyring(construct: string, url: string): string {\n\tconst keyring = parseKeyring(construct, url);\n\tconst next =\n\t\tMath.max(...keyring.keys.map(({ id }) => Number(id.slice(1)) || 0)) + 1;\n\n\treturn formatKeyring({\n\t\t...keyring,\n\t\tkeys: [{ id: `k${next}`, key: randomBytes(KEY_BYTES) }, ...keyring.keys],\n\t});\n}\n\n/** The keyring without `keyId`, which must not be the current key. */\nexport function retireKey(\n\tconstruct: string,\n\turl: string,\n\tkeyId: string,\n): string {\n\tconst keyring = parseKeyring(construct, url);\n\tif (keyring.keys[0]?.id === keyId) {\n\t\tthrow new CurrentKeyCannotRetire(construct, keyId);\n\t}\n\tif (!keyring.keys.some(({ id }) => id === keyId)) {\n\t\tthrow new EncryptionKeyRetired(construct, keyId);\n\t}\n\n\treturn formatKeyring({\n\t\t...keyring,\n\t\tkeys: keyring.keys.filter(({ id }) => id !== keyId),\n\t});\n}\n\n/** Says, once per key per process, that a value is still under an old key. */\nexport type StaleKeyReporter = (keyId: string, current: string) => void;\n\n/** The `aes256gcm://` cipher: a keyring held in process. */\nexport function keyringCipher(\n\tconstruct: string,\n\turl: string,\n\tonStaleKey: StaleKeyReporter = () => {},\n): Cipher {\n\tconst keyring = parseKeyring(construct, url);\n\tconst current = keyring.keys[0]!;\n\tconst byId = new Map(keyring.keys.map(({ id, key }) => [id, key]));\n\tconst reported = new Set<string>();\n\n\tconst decrypt = async (ciphertext: string) => {\n\t\tconst { keyId, payload } = parseCiphertext(construct, ciphertext);\n\t\tconst key = byId.get(keyId);\n\t\tif (!key) throw new EncryptionKeyRetired(construct, keyId);\n\n\t\tconst plaintext = open(key, payload, associatedData(construct, keyId));\n\t\tif (!plaintext) throw new CiphertextNotAuthentic(construct);\n\n\t\tif (keyId !== current.id && !reported.has(keyId)) {\n\t\t\treported.add(keyId);\n\t\t\tonStaleKey(keyId, current.id);\n\t\t}\n\n\t\treturn plaintext.toString('utf8');\n\t};\n\n\tconst encrypt = async (plaintext: string) =>\n\t\tformatCiphertext(\n\t\t\tcurrent.id,\n\t\t\tseal(\n\t\t\t\tcurrent.key,\n\t\t\t\tBuffer.from(plaintext, 'utf8'),\n\t\t\t\tassociatedData(construct, current.id),\n\t\t\t),\n\t\t);\n\n\treturn {\n\t\tencrypt,\n\t\tdecrypt,\n\t\tindex: async (value) =>\n\t\t\tcreateHmac('sha256', keyring.index)\n\t\t\t\t.update(value, 'utf8')\n\t\t\t\t.digest('base64url'),\n\t\treencrypt: async (ciphertext) => {\n\t\t\tconst { keyId } = parseCiphertext(construct, ciphertext);\n\t\t\tif (keyId === current.id) return ciphertext;\n\t\t\treturn encrypt(await decrypt(ciphertext));\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8CA,MAAa,qBAAqB;;AAGlC,MAAM,WAAW;AAEjB,MAAM,YAAY;AAElB,MAAa,eAAe;AAE5B,IAAa,uBAAb,cAA0C,MAAM;CAErC;CACA;CAFV,YACC,WACA,QACC;EACD,MACC,GAAG,UAAU,mCAAmC,OAAO,wJACxD;EALS,KAAA,YAAA;EACA,KAAA,SAAA;EAKT,KAAK,OAAO;CACb;AACD;AAEA,IAAa,0BAAb,cAA6C,MAAM;CAExC;CACA;CAFV,YACC,WACA,QACC;EACD,MACC,GAAG,UAAU,0BAA0B,OAAO,yFAC/C;EALS,KAAA,YAAA;EACA,KAAA,SAAA;EAKT,KAAK,OAAO;CACb;AACD;AAEA,IAAa,sBAAb,cAAyC,MAAM;CACzB;CAArB,YAAY,WAA4B;EACvC,MACC,GAAG,UAAU,yEAAyE,mBAAmB,uEAC1G;EAHoB,KAAA,YAAA;EAIpB,KAAK,OAAO;CACb;AACD;AAEA,IAAa,uBAAb,cAA0C,MAAM;CAErC;CACA;CAFV,YACC,WACA,OACC;EACD,MACC,GAAG,UAAU,eAAe,MAAM,sLACnC;EALS,KAAA,YAAA;EACA,KAAA,QAAA;EAKT,KAAK,OAAO;CACb;AACD;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAC5B;CAArB,YAAY,WAA4B;EACvC,MACC,GAAG,UAAU,8JACd;EAHoB,KAAA,YAAA;EAIpB,KAAK,OAAO;CACb;AACD;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAEvC;CACA;CAFV,YACC,WACA,OACC;EACD,MACC,IAAI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