jazz-tools 0.18.7 → 0.18.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.turbo/turbo-build.log +35 -35
  2. package/CHANGELOG.md +31 -0
  3. package/dist/better-auth/auth/client.d.ts +1 -1
  4. package/dist/better-auth/auth/client.d.ts.map +1 -1
  5. package/dist/better-auth/auth/client.js.map +1 -1
  6. package/dist/better-auth/auth/server.js +1 -1
  7. package/dist/better-auth/auth/server.js.map +1 -1
  8. package/dist/{chunk-CFAY3FMQ.js → chunk-RQHJFPIB.js} +61 -26
  9. package/dist/{chunk-CFAY3FMQ.js.map → chunk-RQHJFPIB.js.map} +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/react/hooks.d.ts +1 -1
  12. package/dist/react/hooks.d.ts.map +1 -1
  13. package/dist/react/index.d.ts +1 -1
  14. package/dist/react/index.d.ts.map +1 -1
  15. package/dist/react/index.js +3 -1
  16. package/dist/react/index.js.map +1 -1
  17. package/dist/react-core/hooks.d.ts +56 -0
  18. package/dist/react-core/hooks.d.ts.map +1 -1
  19. package/dist/react-core/index.js +25 -1
  20. package/dist/react-core/index.js.map +1 -1
  21. package/dist/react-core/tests/useAccountWithSelector.test.d.ts +2 -0
  22. package/dist/react-core/tests/useAccountWithSelector.test.d.ts.map +1 -0
  23. package/dist/react-native-core/hooks.d.ts +1 -1
  24. package/dist/react-native-core/hooks.d.ts.map +1 -1
  25. package/dist/react-native-core/index.js +3 -1
  26. package/dist/react-native-core/index.js.map +1 -1
  27. package/dist/testing.js +1 -1
  28. package/dist/tools/coValues/CoFieldInit.d.ts +5 -5
  29. package/dist/tools/coValues/CoFieldInit.d.ts.map +1 -1
  30. package/dist/tools/implementation/ContextManager.d.ts +2 -0
  31. package/dist/tools/implementation/ContextManager.d.ts.map +1 -1
  32. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts +5 -3
  33. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +1 -1
  34. package/package.json +4 -4
  35. package/src/better-auth/auth/client.ts +1 -1
  36. package/src/better-auth/auth/server.ts +1 -1
  37. package/src/better-auth/auth/tests/client.test.ts +229 -0
  38. package/src/react/hooks.tsx +1 -0
  39. package/src/react/index.ts +1 -0
  40. package/src/react-core/hooks.ts +84 -0
  41. package/src/react-core/tests/useAccountWithSelector.test.ts +411 -0
  42. package/src/react-native-core/hooks.tsx +1 -0
  43. package/src/tools/coValues/CoFieldInit.ts +5 -5
  44. package/src/tools/implementation/ContextManager.ts +75 -32
  45. package/src/tools/implementation/zodSchema/schemaTypes/CoMapSchema.ts +22 -8
  46. package/src/tools/tests/ContextManager.test.ts +252 -0
  47. package/src/tools/tests/coMap.test.ts +37 -0
@@ -1,5 +1,5 @@
1
1
 
2
- > jazz-tools@0.18.7 build /home/runner/_work/jazz/jazz/packages/jazz-tools
2
+ > jazz-tools@0.18.10 build /home/runner/_work/jazz/jazz/packages/jazz-tools
3
3
  > tsup && pnpm types && pnpm build:svelte
4
4
 
5
5
  CLI Building entry: {"index":"src/index.ts","testing":"src/testing.ts"}
@@ -109,23 +109,20 @@
109
109
  ESM Build start
110
110
  ESM dist/react/ssr.js 688.00 B
111
111
  ESM dist/react/ssr.js.map 1.12 KB
112
- ESM ⚡️ Build success in 21ms
112
+ ESM ⚡️ Build success in 26ms
113
113
  ESM dist/worker/index.js 2.47 KB
114
114
  ESM dist/worker/index.js.map 5.26 KB
115
- ESM ⚡️ Build success in 18ms
115
+ ESM ⚡️ Build success in 22ms
116
116
  ESM dist/tiptap/index.js 564.00 B
117
117
  ESM dist/tiptap/index.js.map 1.21 KB
118
- ESM ⚡️ Build success in 20ms
118
+ ESM ⚡️ Build success in 22ms
119
119
  ESM dist/better-auth/auth/client.js 4.44 KB
120
+ ESM dist/better-auth/auth/server.js 8.36 KB
120
121
  ESM dist/better-auth/auth/react.js 799.00 B
121
- ESM dist/better-auth/auth/server.js 8.35 KB
122
122
  ESM dist/better-auth/auth/client.js.map 8.24 KB
123
+ ESM dist/better-auth/auth/server.js.map 15.29 KB
123
124
  ESM dist/better-auth/auth/react.js.map 2.04 KB
124
- ESM dist/better-auth/auth/server.js.map 15.28 KB
125
- ESM ⚡️ Build success in 23ms
126
- ESM dist/browser/index.js 13.64 KB
127
- ESM dist/browser/index.js.map 29.14 KB
128
- ESM ⚡️ Build success in 37ms
125
+ ESM ⚡️ Build success in 25ms
129
126
  ESM dist/media/index.js 236.00 B
130
127
  ESM dist/media/index.browser.js 2.79 KB
131
128
  ESM dist/media/index.native.js 2.90 KB
@@ -136,64 +133,67 @@
136
133
  ESM dist/media/index.native.js.map 6.09 KB
137
134
  ESM dist/media/index.server.js.map 6.37 KB
138
135
  ESM dist/media/chunk-W3S526L3.js.map 16.57 KB
139
- ESM ⚡️ Build success in 37ms
136
+ ESM ⚡️ Build success in 40ms
140
137
  ESM dist/expo/index.js 4.68 KB
141
138
  ESM dist/expo/testing.js 112.00 B
142
139
  ESM dist/expo/crypto.js 153.00 B
143
140
  ESM dist/expo/index.js.map 10.23 KB
144
141
  ESM dist/expo/testing.js.map 168.00 B
145
142
  ESM dist/expo/crypto.js.map 189.00 B
146
- ESM ⚡️ Build success in 37ms
143
+ ESM ⚡️ Build success in 40ms
147
144
  ESM dist/react-native/index.js 2.53 KB
148
145
  ESM dist/react-native/testing.js 120.00 B
149
146
  ESM dist/react-native/crypto.js 161.00 B
150
- ESM dist/react-native/testing.js.map 176.00 B
151
147
  ESM dist/react-native/index.js.map 5.68 KB
148
+ ESM dist/react-native/testing.js.map 176.00 B
152
149
  ESM dist/react-native/crypto.js.map 197.00 B
153
- ESM ⚡️ Build success in 44ms
150
+ ESM ⚡️ Build success in 36ms
151
+ ESM dist/browser/index.js 13.64 KB
152
+ ESM dist/browser/index.js.map 29.14 KB
153
+ ESM ⚡️ Build success in 41ms
154
+ ESM dist/react-native-core/index.js 18.00 KB
155
+ ESM dist/react-native-core/testing.js 119.00 B
156
+ ESM dist/react-native-core/crypto.js 2.10 KB
157
+ ESM dist/react-native-core/index.js.map 36.73 KB
158
+ ESM dist/react-native-core/testing.js.map 175.00 B
159
+ ESM dist/react-native-core/crypto.js.map 4.25 KB
160
+ ESM ⚡️ Build success in 46ms
154
161
  ESM dist/prosemirror/index.js 77.63 KB
155
162
  ESM dist/prosemirror/index.js.map 306.98 KB
156
- ESM ⚡️ Build success in 50ms
163
+ ESM ⚡️ Build success in 49ms
164
+ ESM dist/react/index.js 24.76 KB
157
165
  ESM dist/react/testing.js 122.00 B
158
- ESM dist/react/index.js 24.71 KB
166
+ ESM dist/react/index.js.map 53.56 KB
159
167
  ESM dist/react/testing.js.map 165.00 B
160
- ESM dist/react/index.js.map 53.50 KB
161
- ESM ⚡️ Build success in 51ms
162
- ESM dist/react-native-core/index.js 17.95 KB
163
- ESM dist/react-native-core/crypto.js 2.10 KB
164
- ESM dist/react-native-core/testing.js 119.00 B
165
- ESM dist/react-native-core/index.js.map 36.70 KB
166
- ESM dist/react-native-core/crypto.js.map 4.25 KB
167
- ESM dist/react-native-core/testing.js.map 175.00 B
168
- ESM ⚡️ Build success in 53ms
168
+ ESM ⚡️ Build success in 49ms
169
169
  ESM dist/inspector/index.js 69.71 KB
170
170
  ESM dist/inspector/index.js.map 121.38 KB
171
- ESM ⚡️ Build success in 72ms
171
+ ESM ⚡️ Build success in 61ms
172
172
  ESM dist/testing.js 7.17 KB
173
173
  ESM dist/index.js 26.13 KB
174
- ESM dist/chunk-CFAY3FMQ.js 168.48 KB
174
+ ESM dist/chunk-RQHJFPIB.js 169.74 KB
175
175
  ESM dist/testing.js.map 14.10 KB
176
176
  ESM dist/index.js.map 52.92 KB
177
- ESM dist/chunk-CFAY3FMQ.js.map 400.30 KB
178
- ESM ⚡️ Build success in 105ms
177
+ ESM dist/chunk-RQHJFPIB.js.map 402.59 KB
178
+ ESM ⚡️ Build success in 88ms
179
+ ESM dist/react-core/index.js 146.19 KB
179
180
  ESM dist/react-core/testing.js 1.17 KB
180
181
  ESM dist/react-core/chunk-7DYMJ74I.js 279.00 B
181
- ESM dist/react-core/index.js 145.49 KB
182
182
  ESM dist/react-core/testing.js.map 1.82 KB
183
183
  ESM dist/react-core/chunk-7DYMJ74I.js.map 533.00 B
184
- ESM dist/react-core/index.js.map 399.32 KB
185
- ESM ⚡️ Build success in 106ms
184
+ ESM dist/react-core/index.js.map 404.45 KB
185
+ ESM ⚡️ Build success in 90ms
186
186
  ESM dist/inspector/register-custom-element.js 218.00 B
187
187
  ESM dist/inspector/register-custom-element.js.map 314.00 B
188
188
  ESM dist/inspector/custom-element-G6SPZEBR.js 1.54 MB
189
189
  ESM dist/inspector/custom-element-G6SPZEBR.js.map 2.36 MB
190
- ESM ⚡️ Build success in 148ms
190
+ ESM ⚡️ Build success in 122ms
191
191
 
192
- > jazz-tools@0.18.7 types /home/runner/_work/jazz/jazz/packages/jazz-tools
192
+ > jazz-tools@0.18.10 types /home/runner/_work/jazz/jazz/packages/jazz-tools
193
193
  > tsc --outDir dist
194
194
 
195
195
 
196
- > jazz-tools@0.18.7 build:svelte /home/runner/_work/jazz/jazz/packages/jazz-tools
196
+ > jazz-tools@0.18.10 build:svelte /home/runner/_work/jazz/jazz/packages/jazz-tools
197
197
  > rm -rf dist/svelte && svelte-package -i src/svelte -o dist/svelte --tsconfig tsconfig.svelte.json
198
198
 
199
199
  src/svelte -> dist/svelte
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # jazz-tools
2
2
 
3
+ ## 0.18.10
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [95cc9af]
8
+ - cojson-transport-ws@0.18.10
9
+ - cojson@0.18.10
10
+ - cojson-storage-indexeddb@0.18.10
11
+
12
+ ## 0.18.9
13
+
14
+ ### Patch Changes
15
+
16
+ - c8167de: fix: improve handling of concurrent authentication attempts in ContextManager
17
+ - 910b8d6: Added useAccountWithSelector hook for granular account data selection with custom equality checking
18
+ - Updated dependencies [f058875]
19
+ - cojson@0.18.9
20
+ - cojson-storage-indexeddb@0.18.9
21
+ - cojson-transport-ws@0.18.9
22
+
23
+ ## 0.18.8
24
+
25
+ ### Patch Changes
26
+
27
+ - 700fe46: fix: in 32d1444 was used the wrong Better Auth internal function to delete old verification codes
28
+ - aba0d55: Support the selection of a subset of keys to make optional in `co.map().partial()`
29
+ - Updated dependencies [9a4caf2]
30
+ - cojson@0.18.8
31
+ - cojson-storage-indexeddb@0.18.8
32
+ - cojson-transport-ws@0.18.8
33
+
3
34
  ## 0.18.7
4
35
 
5
36
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- import type { AuthSecretStorage, Account, JazzContextType } from "jazz-tools";
1
+ import type { Account, AuthSecretStorage, JazzContextType } from "jazz-tools";
2
2
  import type { jazzPlugin } from "./server.js";
3
3
  /**
4
4
  * @example
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/better-auth/auth/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EAEjB,OAAO,EACP,eAAe,EAChB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAS9C;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB;;wBAmBC,UAAU,CAAC,OAAO,UAAU,CAAC;;;sCAIvB,eAAe,CAAC,OAAO,CAAC;4CAGlB,iBAAiB;;;;;;;;;;;CA4H1D,CAAC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/better-auth/auth/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,OAAO,EACP,iBAAiB,EAEjB,eAAe,EAChB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAS9C;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB;;wBAmBC,UAAU,CAAC,OAAO,UAAU,CAAC;;;sCAIvB,eAAe,CAAC,OAAO,CAAC;4CAGlB,iBAAiB;;;;;;;;;;;CA4H1D,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/better-auth/auth/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type {\n AuthSecretStorage,\n AuthSetPayload,\n Account,\n JazzContextType,\n} from \"jazz-tools\";\nimport type { jazzPlugin } from \"./server.js\";\n\nconst SIGNUP_URLS = [\n \"/sign-up\",\n \"/sign-in/social\",\n \"/sign-in/oauth2\",\n \"/email-otp/send-verification-otp\",\n];\n\n/**\n * @example\n * ```ts\n * const auth = betterAuth({\n * plugins: [jazzPluginClient()],\n * });\n * ```\n */\nexport const jazzPluginClient = () => {\n let jazzContext: JazzContextType<Account>;\n let authSecretStorage: AuthSecretStorage;\n let signOutUnsubscription: () => void;\n\n const authenticateOnJazz = async (jazzAuth: AuthSetPayload) => {\n const parsedJazzAuth = {\n ...jazzAuth,\n secretSeed: jazzAuth.secretSeed\n ? Uint8Array.from(jazzAuth.secretSeed)\n : undefined,\n };\n\n await jazzContext.authenticate(parsedJazzAuth);\n await authSecretStorage.set(parsedJazzAuth);\n };\n\n return {\n id: \"jazz-plugin\",\n $InferServerPlugin: {} as ReturnType<typeof jazzPlugin>,\n getActions: ($fetch, $store) => {\n return {\n jazz: {\n setJazzContext: (context: JazzContextType<Account>) => {\n jazzContext = context;\n },\n setAuthSecretStorage: (storage: AuthSecretStorage) => {\n authSecretStorage = storage;\n if (signOutUnsubscription) signOutUnsubscription();\n\n // This is a workaround to logout from Better Auth when user logs out directly from Jazz\n signOutUnsubscription = authSecretStorage.onUpdate(\n (isAuthenticated) => {\n if (isAuthenticated === false) {\n const session = $store.atoms.session?.get();\n if (!session) return;\n\n // if the user logs out from Better Auth, the get session is immediately called\n // so we must wait the next fetched session to understand if we need to call sign-out\n if (session.isPending || session.isRefetching) {\n // listen once for next session's data\n const unsub = $store.atoms.session?.listen((session) => {\n unsub?.();\n // if the session is null, user has been already logged out from Better Auth\n if (session.data !== null) {\n $fetch(\"/sign-out\", { method: \"POST\" });\n }\n });\n }\n // if the session is not pending, it means user logged out from Jazz only\n // so we call the sign-out api\n else {\n $fetch(\"/sign-out\", { method: \"POST\" });\n }\n }\n },\n );\n },\n },\n };\n },\n fetchPlugins: [\n {\n id: \"jazz-plugin\",\n name: \"jazz-plugin\",\n hooks: {\n async onRequest(context) {\n if (\n SIGNUP_URLS.some((url) => context.url.toString().includes(url))\n ) {\n const credentials = await authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"Jazz credentials not found\");\n }\n\n context.headers.set(\n \"x-jazz-auth\",\n JSON.stringify({\n accountID: credentials.accountID,\n secretSeed: credentials.secretSeed,\n accountSecret: credentials.accountSecret,\n }),\n );\n }\n },\n async onSuccess(context) {\n if (context.request.url.toString().includes(\"/sign-up\")) {\n await authenticateOnJazz(context.data.jazzAuth);\n return;\n }\n\n if (context.request.url.toString().includes(\"/sign-in/email\")) {\n await authenticateOnJazz(context.data.jazzAuth);\n return;\n }\n\n if (context.request.url.toString().includes(\"/get-session\")) {\n if (context.data === null) {\n if (authSecretStorage.isAuthenticated === true) {\n console.warn(\n \"Jazz is authenticated, but the session is null\",\n );\n }\n return;\n }\n\n if (!context.data?.user) {\n return;\n }\n\n if (authSecretStorage.isAuthenticated === false) {\n console.info(\n \"Jazz is not authenticated, using Better Auth stored credentials\",\n );\n await authenticateOnJazz(context.data.jazzAuth);\n return;\n }\n\n const sessionAccountID = context.data.user.accountID;\n\n const credentials = await authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"Jazz credentials not found\");\n }\n\n if (credentials.accountID !== sessionAccountID) {\n console.info(\n \"Jazz credentials mismatch, using Better Auth stored credentials\",\n );\n await authenticateOnJazz(context.data.jazzAuth);\n }\n return;\n }\n\n if (context.request.url.toString().includes(\"/sign-out\")) {\n await jazzContext.logOut();\n return;\n }\n\n if (context.request.url.toString().includes(\"/delete-user\")) {\n await jazzContext.logOut();\n return;\n }\n },\n },\n },\n ],\n } satisfies BetterAuthClientPl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C9C;AAEA,kBAAI,YAAY,cAAc,kBAAkB;AAC9C,wBAAQ;AAAA,kBACN;AAAA,gBACF;AACA,sBAAM,mBAAmB,QAAQ,KAAK,QAAQ;AAAA,cAChD;AACA;AAAA,YACF;AAEA,gBAAI,QAAQ,QAAQ,IAAI,SAAS,EAAE,SAAS,WAAW,GAAG;AACxD,oBAAM,YAAY,OAAO;AACzB;AAAA,YACF;AAEA,gBAAI,QAAQ,QAAQ,IAAI,SAAS,EAAE,SAAS,cAAc,GAAG;AAC3D,oBAAM,YAAY,OAAO;AACzB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["session"]}
1
+ {"version":3,"sources":["../../../src/better-auth/auth/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type {\n Account,\n AuthSecretStorage,\n AuthSetPayload,\n JazzContextType,\n} from \"jazz-tools\";\nimport type { jazzPlugin } from \"./server.js\";\n\nconst SIGNUP_URLS = [\n \"/sign-up\",\n \"/sign-in/social\",\n \"/sign-in/oauth2\",\n \"/email-otp/send-verification-otp\",\n];\n\n/**\n * @example\n * ```ts\n * const auth = betterAuth({\n * plugins: [jazzPluginClient()],\n * });\n * ```\n */\nexport const jazzPluginClient = () => {\n let jazzContext: JazzContextType<Account>;\n let authSecretStorage: AuthSecretStorage;\n let signOutUnsubscription: () => void;\n\n const authenticateOnJazz = async (jazzAuth: AuthSetPayload) => {\n const parsedJazzAuth = {\n ...jazzAuth,\n secretSeed: jazzAuth.secretSeed\n ? Uint8Array.from(jazzAuth.secretSeed)\n : undefined,\n };\n\n await jazzContext.authenticate(parsedJazzAuth);\n await authSecretStorage.set(parsedJazzAuth);\n };\n\n return {\n id: \"jazz-plugin\",\n $InferServerPlugin: {} as ReturnType<typeof jazzPlugin>,\n getActions: ($fetch, $store) => {\n return {\n jazz: {\n setJazzContext: (context: JazzContextType<Account>) => {\n jazzContext = context;\n },\n setAuthSecretStorage: (storage: AuthSecretStorage) => {\n authSecretStorage = storage;\n if (signOutUnsubscription) signOutUnsubscription();\n\n // This is a workaround to logout from Better Auth when user logs out directly from Jazz\n signOutUnsubscription = authSecretStorage.onUpdate(\n (isAuthenticated) => {\n if (isAuthenticated === false) {\n const session = $store.atoms.session?.get();\n if (!session) return;\n\n // if the user logs out from Better Auth, the get session is immediately called\n // so we must wait the next fetched session to understand if we need to call sign-out\n if (session.isPending || session.isRefetching) {\n // listen once for next session's data\n const unsub = $store.atoms.session?.listen((session) => {\n unsub?.();\n // if the session is null, user has been already logged out from Better Auth\n if (session.data !== null) {\n $fetch(\"/sign-out\", { method: \"POST\" });\n }\n });\n }\n // if the session is not pending, it means user logged out from Jazz only\n // so we call the sign-out api\n else {\n $fetch(\"/sign-out\", { method: \"POST\" });\n }\n }\n },\n );\n },\n },\n };\n },\n fetchPlugins: [\n {\n id: \"jazz-plugin\",\n name: \"jazz-plugin\",\n hooks: {\n async onRequest(context) {\n if (\n SIGNUP_URLS.some((url) => context.url.toString().includes(url))\n ) {\n const credentials = await authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"Jazz credentials not found\");\n }\n\n context.headers.set(\n \"x-jazz-auth\",\n JSON.stringify({\n accountID: credentials.accountID,\n secretSeed: credentials.secretSeed,\n accountSecret: credentials.accountSecret,\n }),\n );\n }\n },\n async onSuccess(context) {\n if (context.request.url.toString().includes(\"/sign-up\")) {\n await authenticateOnJazz(context.data.jazzAuth);\n return;\n }\n\n if (context.request.url.toString().includes(\"/sign-in/email\")) {\n await authenticateOnJazz(context.data.jazzAuth);\n return;\n }\n\n if (context.request.url.toString().includes(\"/get-session\")) {\n if (context.data === null) {\n if (authSecretStorage.isAuthenticated === true) {\n console.warn(\n \"Jazz is authenticated, but the session is null\",\n );\n }\n return;\n }\n\n if (!context.data?.user) {\n return;\n }\n\n if (authSecretStorage.isAuthenticated === false) {\n console.info(\n \"Jazz is not authenticated, using Better Auth stored credentials\",\n );\n await authenticateOnJazz(context.data.jazzAuth);\n return;\n }\n\n const sessionAccountID = context.data.user.accountID;\n\n const credentials = await authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"Jazz credentials not found\");\n }\n\n if (credentials.accountID !== sessionAccountID) {\n console.info(\n \"Jazz credentials mismatch, using Better Auth stored credentials\",\n );\n await authenticateOnJazz(context.data.jazzAuth);\n }\n return;\n }\n\n if (context.request.url.toString().includes(\"/sign-out\")) {\n await jazzContext.logOut();\n return;\n }\n\n if (context.request.url.toString().includes(\"/delete-user\")) {\n await jazzContext.logOut();\n return;\n }\n },\n },\n },\n ],\n } satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";AASA,IAAM,cAAc;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,mBAAmB,MAAM;AACpC,MAAI;AACJ,MAAI;AACJ,MAAI;AAEJ,QAAM,qBAAqB,OAAO,aAA6B;AAC7D,UAAM,iBAAiB;AAAA,MACrB,GAAG;AAAA,MACH,YAAY,SAAS,aACjB,WAAW,KAAK,SAAS,UAAU,IACnC;AAAA,IACN;AAEA,UAAM,YAAY,aAAa,cAAc;AAC7C,UAAM,kBAAkB,IAAI,cAAc;AAAA,EAC5C;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,oBAAoB,CAAC;AAAA,IACrB,YAAY,CAAC,QAAQ,WAAW;AAC9B,aAAO;AAAA,QACL,MAAM;AAAA,UACJ,gBAAgB,CAAC,YAAsC;AACrD,0BAAc;AAAA,UAChB;AAAA,UACA,sBAAsB,CAAC,YAA+B;AACpD,gCAAoB;AACpB,gBAAI,sBAAuB,uBAAsB;AAGjD,oCAAwB,kBAAkB;AAAA,cACxC,CAAC,oBAAoB;AACnB,oBAAI,oBAAoB,OAAO;AAC7B,wBAAM,UAAU,OAAO,MAAM,SAAS,IAAI;AAC1C,sBAAI,CAAC,QAAS;AAId,sBAAI,QAAQ,aAAa,QAAQ,cAAc;AAE7C,0BAAM,QAAQ,OAAO,MAAM,S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;AAAA,kBACF;AAAA,gBACF;AACA;AAAA,cACF;AAEA,kBAAI,CAAC,QAAQ,MAAM,MAAM;AACvB;AAAA,cACF;AAEA,kBAAI,kBAAkB,oBAAoB,OAAO;AAC/C,wBAAQ;AAAA,kBACN;AAAA,gBACF;AACA,sBAAM,mBAAmB,QAAQ,KAAK,QAAQ;AAC9C;AAAA,cACF;AAEA,oBAAM,mBAAmB,QAAQ,KAAK,KAAK;AAE3C,oBAAM,cAAc,MAAM,kBAAkB,IAAI;AAEhD,kBAAI,CAAC,aAAa;AAChB,sBAAM,IAAI,MAAM,4BAA4B;AAAA,cAC9C;AAEA,kBAAI,YAAY,cAAc,kBAAkB;AAC9C,wBAAQ;AAAA,kBACN;AAAA,gBACF;AACA,sBAAM,mBAAmB,QAAQ,KAAK,QAAQ;AAAA,cAChD;AACA;AAAA,YACF;AAEA,gBAAI,QAAQ,QAAQ,IAAI,SAAS,EAAE,SAAS,WAAW,GAAG;AACxD,oBAAM,YAAY,OAAO;AACzB;AAAA,YACF;AAEA,gBAAI,QAAQ,QAAQ,IAAI,SAAS,EAAE,SAAS,cAAc,GAAG;AAC3D,oBAAM,YAAY,OAAO;AACzB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["session"]}
@@ -48,7 +48,7 @@ var jazzPlugin = () => {
48
48
  after: async (verification, context) => {
49
49
  if (contextContainsJazzAuth(context) && verification.identifier.startsWith("sign-in-otp-")) {
50
50
  const identifier = `jazz-auth-${verification.identifier}`;
51
- await context.context.internalAdapter.deleteVerificationValue(
51
+ await context.context.internalAdapter.deleteVerificationByIdentifier(
52
52
  identifier
53
53
  );
54
54
  await context.context.internalAdapter.createVerificationValue(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/better-auth/auth/server.ts"],"sourcesContent":["import { AuthContext, MiddlewareContext, MiddlewareOptions } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"better-auth/crypto\";\nimport { BetterAuthPlugin, createAuthMiddleware } from \"better-auth/plugins\";\nimport type { Account, AuthCredentials, ID } from \"jazz-tools\";\n\n// Define a type to have user fields mapped in the better-auth instance\n// It should be automatic, but it needs an hard reference to BetterAuthPlugin type\n// in order to be exported as library.\ntype JazzPlugin = BetterAuthPlugin & {\n schema: {\n user: {\n fields: {\n accountID: {\n type: \"string\";\n required: false;\n input: false;\n };\n encryptedCredentials: {\n type: \"string\";\n required: false;\n input: false;\n returned: false;\n };\n };\n };\n };\n};\n\n/**\n * @returns The BetterAuth server plugin.\n *\n * @example\n * ```ts\n * const auth = betterAuth({\n * plugins: [jazzPlugin()],\n * // ... other BetterAuth options\n * });\n * ```\n */\nexport const jazzPlugin: () => JazzPlugin = () => {\n return {\n id: \"jazz-plugin\",\n schema: {\n user: {\n fields: {\n accountID: {\n type: \"string\",\n required: false,\n input: false,\n },\n encryptedCredentials: {\n type: \"string\",\n required: false,\n input: false,\n returned: false,\n },\n },\n },\n },\n\n init() {\n return {\n options: {\n databaseHooks: {\n user: {\n create: {\n before: async (user, context) => {\n // If the user is created without a jazzAuth, it will throw an error.\n if (!contextContainsJazzAuth(context)) {\n throw new APIError(422, {\n message: \"JazzAuth is required on user creation\",\n });\n }\n // Decorate the user with the jazz's credentials.\n return {\n data: {\n accountID: context.jazzAuth.accountID,\n encryptedCredentials:\n context.jazzAuth.encryptedCredentials,\n },\n };\n },\n },\n },\n verification: {\n create: {\n after: async (verification, context) => {\n /**\n * For: Email OTP plugin\n * After a verification is created, if it is from the EmailOTP plugin,\n * create a new verification value with the jazzAuth with the same expiration.\n */\n if (\n contextContainsJazzAuth(context) &&\n verification.identifier.startsWith(\"sign-in-otp-\")\n ) {\n const identifier = `jazz-auth-${verification.identifier}`;\n await context.context.internalAdapter.deleteVerificationValue(\n identifier,\n );\n await context.context.internalAdapter.createVerificationValue(\n {\n value: JSON.stringify({ jazzAuth: context.jazzAuth }),\n identifier: identifier,\n expiresAt: verification.expiresAt,\n },\n );\n }\n },\n },\n },\n },\n },\n };\n },\n\n hooks: {\n before: [\n /**\n * If the client sends a x-jazz-auth header,\n * we encrypt the credentials and inject them into the context.\n */\n {\n matcher: (context) => {\n return !!context.headers?.get(\"x-jazz-auth\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const jazzAuth = JSON.parse(ctx.headers?.get(\"x-jazz-auth\")!);\n\n const credentials: AuthCredentials = {\n accountID: jazzAuth.accountID as ID<Account>,\n secretSeed: jazzAuth.secretSeed,\n accountSecret: jazzAuth.accountSecret as any,\n // If the provider remains 'anonymous', Jazz will not consider us authenticated later.\n provider: \"better-auth\",\n };\n\n const encryptedCredentials = await symmetricEncrypt({\n key: ctx.context.secret,\n data: JSON.stringify(credentials),\n });\n\n return {\n context: {\n ...ctx,\n jazzAuth: {\n accountID: jazzAuth.accountID,\n encryptedCredentials: encryptedCredentials,\n },\n },\n };\n }),\n },\n\n /**\n * For: Social / OAuth2 plugin\n * /callback is the endpoint that BetterAuth uses to authenticate the user coming from a social provider.\n * 1. Catch the state\n * 2. Find the verification value\n * 3. If the verification value contains a jazzAuth, inject into the context to have it in case of registration.\n */\n {\n matcher: (context) => {\n return (\n context.path.startsWith(\"/callback\") ||\n context.path.startsWith(\"/oauth2/callback\")\n );\n },\n handler: createAuthMiddleware(async (ctx) => {\n const state = ctx.query?.state || ctx.body?.state;\n\n const identifier = `jazz-auth-${state}`;\n\n const data =\n await ctx.context.internalAdapter.findVerificationValue(\n identifier,\n );\n\n // if not found, the social plugin will throw later anyway\n if (!data) {\n throw new APIError(404, {\n message: \"Verification not found\",\n });\n }\n\n const parsed = JSON.parse(data.value);\n\n if (parsed && \"jazzAuth\" in parsed) {\n return {\n context: {\n ...ctx,\n jazzAuth: parsed.jazzAuth,\n },\n };\n } else {\n throw new APIError(404, {\n message: \"JazzAuth not found in verification value\",\n });\n }\n }),\n },\n /**\n * For: Email OTP plugin\n * When the user sends an OTP, we try to find the jazzAuth.\n * If it isn't a sign-up, we expect to not find a verification value.\n */\n {\n matcher: (context) => {\n return context.path.startsWith(\"/sign-in/email-otp\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const email = ctx.body.email;\n const identifier = `jazz-auth-sign-in-otp-${email}`;\n\n const data =\n await ctx.context.internalAdapter.findVerificationValue(\n identifier,\n );\n\n // if not found, it isn't a sign-up\n if (!data || data.expiresAt < new Date()) {\n return;\n }\n\n const parsed = JSON.parse(data.value);\n\n if (parsed && \"jazzAuth\" in parsed) {\n return {\n context: {\n ...ctx,\n jazzAuth: parsed.jazzAuth,\n },\n };\n } else {\n throw new APIError(500, {\n message: \"JazzAuth not found in verification value\",\n });\n }\n }),\n },\n ],\n after: [\n /**\n * This middleware is used to extract the jazzAuth from the user and return it in the response.\n * It is used in the following endpoints that return the user:\n * - /sign-up/email\n * - /sign-in/email\n * - /get-session\n */\n {\n matcher: (context) => {\n return (\n context.path.startsWith(\"/sign-up\") ||\n context.path.startsWith(\"/sign-in\") ||\n context.path.startsWith(\"/get-session\")\n );\n },\n handler: createAuthMiddleware({}, async (ctx) => {\n const returned = ctx.context.returned as any;\n if (!returned?.user?.id) {\n return;\n }\n const jazzAuth = await extractJazzAuth(returned.user.id, ctx);\n\n return ctx.json({\n ...returned,\n jazzAuth: jazzAuth,\n });\n }),\n },\n\n /**\n * For: Social / OAuth2 plugin\n * When the user sign-in via social, we create a verification value with the jazzAuth.\n */\n {\n matcher: (context) => {\n return context.path.startsWith(\"/sign-in/social\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n if (!contextContainsJazzAuth(ctx)) {\n throw new APIError(500, {\n message: \"JazzAuth not found in context\",\n });\n }\n\n const returned = ctx.context.returned as { url: string };\n\n const url = new URL(returned.url);\n const state = url.searchParams.get(\"state\");\n\n const value = JSON.stringify({ jazzAuth: ctx.jazzAuth });\n const expiresAt = new Date();\n expiresAt.setMinutes(expiresAt.getMinutes() + 10);\n\n await ctx.context.internalAdapter.createVerificationValue({\n value,\n identifier: `jazz-auth-${state}`,\n expiresAt,\n });\n }),\n },\n ],\n },\n } satisfies JazzPlugin;\n};\n\nfunction contextContainsJazzAuth(ctx: unknown): ctx is {\n jazzAuth: {\n accountID: string;\n encryptedCredentials: string;\n };\n} {\n return !!ctx && typeof ctx === \"object\" && \"jazzAuth\" in ctx;\n}\n\nasync function extractJazzAuth(\n userId: string,\n ctx: MiddlewareContext<\n MiddlewareOptions,\n AuthContext & {\n returned?: unknown;\n responseHeaders?: Headers;\n }\n >,\n) {\n const user = await ctx.context.adapter.findOne<{\n accountID: string;\n encryptedCredentials: string;\n }>({\n model: ctx.context.tables.user!.modelName,\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: userId,\n },\n ],\n select: [\"accountID\", \"encryptedCredentials\"],\n });\n\n if (!user) {\n return;\n }\n\n const jazzAuth = JSON.parse(\n await symmetricDecrypt({\n key: ctx.context.secret,\n data: user.encryptedCredentials,\n }),\n );\n\n return jazzAuth;\n}\n"],"mappings":";AACA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB,wBAAwB;AACnD,SAA2B,4BAA4B;AAqChD,IAAM,aAA+B,MAAM;AAChD,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,QAAQ;AAAA,MACN,MAAM;AAAA,QACJ,QAAQ;AAAA,UACN,WAAW;AAAA,YACT,MAAM;AAAA,YACN,UAAU;AAAA,YACV,OAAO;AAAA,UACT;AAAA,UACA,sBAAsB;AAAA,YACpB,MAAM;AAAA,YACN,UAAU;AAAA,YACV,OAAO;AAAA,YACP,UAAU;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,OAAO;AACL,aAAO;AAAA,QACL,SAAS;AAAA,UACP,eAAe;AAAA,YACb,MAAM;AAAA,cACJ,QAAQ;AAAA,gBACN,QAAQ,OAAO,MAAM,YAAY;AAE/B,sBAAI,CAAC,wBAAwB,OAAO,GAAG;AACrC,0BAAM,IAAI,SAAS,KAAK;AAAA,sBACtB,SAAS;AAAA,oBACX,CAAC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C,kBAAM,QAAQ,KAAK,UAAU,EAAE,UAAU,IAAI,SAAS,CAAC;AACvD,kBAAM,YAAY,oBAAI,KAAK;AAC3B,sBAAU,WAAW,UAAU,WAAW,IAAI,EAAE;AAEhD,kBAAM,IAAI,QAAQ,gBAAgB,wBAAwB;AAAA,cACxD;AAAA,cACA,YAAY,aAAa,KAAK;AAAA,cAC9B;AAAA,YACF,CAAC;AAAA,UACH,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,wBAAwB,KAK/B;AACA,SAAO,CAAC,CAAC,OAAO,OAAO,QAAQ,YAAY,cAAc;AAC3D;AAEA,eAAe,gBACb,QACA,KAOA;AACA,QAAM,OAAO,MAAM,IAAI,QAAQ,QAAQ,QAGpC;AAAA,IACD,OAAO,IAAI,QAAQ,OAAO,KAAM;AAAA,IAChC,OAAO;AAAA,MACL;AAAA,QACE,OAAO;AAAA,QACP,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,aAAa,sBAAsB;AAAA,EAC9C,CAAC;AAED,MAAI,CAAC,MAAM;AACT;AAAA,EACF;AAEA,QAAM,WAAW,KAAK;AAAA,IACpB,MAAM,iBAAiB;AAAA,MACrB,KAAK,IAAI,QAAQ;AAAA,MACjB,MAAM,KAAK;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/better-auth/auth/server.ts"],"sourcesContent":["import { AuthContext, MiddlewareContext, MiddlewareOptions } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport { symmetricDecrypt, symmetricEncrypt } from \"better-auth/crypto\";\nimport { BetterAuthPlugin, createAuthMiddleware } from \"better-auth/plugins\";\nimport type { Account, AuthCredentials, ID } from \"jazz-tools\";\n\n// Define a type to have user fields mapped in the better-auth instance\n// It should be automatic, but it needs an hard reference to BetterAuthPlugin type\n// in order to be exported as library.\ntype JazzPlugin = BetterAuthPlugin & {\n schema: {\n user: {\n fields: {\n accountID: {\n type: \"string\";\n required: false;\n input: false;\n };\n encryptedCredentials: {\n type: \"string\";\n required: false;\n input: false;\n returned: false;\n };\n };\n };\n };\n};\n\n/**\n * @returns The BetterAuth server plugin.\n *\n * @example\n * ```ts\n * const auth = betterAuth({\n * plugins: [jazzPlugin()],\n * // ... other BetterAuth options\n * });\n * ```\n */\nexport const jazzPlugin: () => JazzPlugin = () => {\n return {\n id: \"jazz-plugin\",\n schema: {\n user: {\n fields: {\n accountID: {\n type: \"string\",\n required: false,\n input: false,\n },\n encryptedCredentials: {\n type: \"string\",\n required: false,\n input: false,\n returned: false,\n },\n },\n },\n },\n\n init() {\n return {\n options: {\n databaseHooks: {\n user: {\n create: {\n before: async (user, context) => {\n // If the user is created without a jazzAuth, it will throw an error.\n if (!contextContainsJazzAuth(context)) {\n throw new APIError(422, {\n message: \"JazzAuth is required on user creation\",\n });\n }\n // Decorate the user with the jazz's credentials.\n return {\n data: {\n accountID: context.jazzAuth.accountID,\n encryptedCredentials:\n context.jazzAuth.encryptedCredentials,\n },\n };\n },\n },\n },\n verification: {\n create: {\n after: async (verification, context) => {\n /**\n * For: Email OTP plugin\n * After a verification is created, if it is from the EmailOTP plugin,\n * create a new verification value with the jazzAuth with the same expiration.\n */\n if (\n contextContainsJazzAuth(context) &&\n verification.identifier.startsWith(\"sign-in-otp-\")\n ) {\n const identifier = `jazz-auth-${verification.identifier}`;\n await context.context.internalAdapter.deleteVerificationByIdentifier(\n identifier,\n );\n await context.context.internalAdapter.createVerificationValue(\n {\n value: JSON.stringify({ jazzAuth: context.jazzAuth }),\n identifier: identifier,\n expiresAt: verification.expiresAt,\n },\n );\n }\n },\n },\n },\n },\n },\n };\n },\n\n hooks: {\n before: [\n /**\n * If the client sends a x-jazz-auth header,\n * we encrypt the credentials and inject them into the context.\n */\n {\n matcher: (context) => {\n return !!context.headers?.get(\"x-jazz-auth\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const jazzAuth = JSON.parse(ctx.headers?.get(\"x-jazz-auth\")!);\n\n const credentials: AuthCredentials = {\n accountID: jazzAuth.accountID as ID<Account>,\n secretSeed: jazzAuth.secretSeed,\n accountSecret: jazzAuth.accountSecret as any,\n // If the provider remains 'anonymous', Jazz will not consider us authenticated later.\n provider: \"better-auth\",\n };\n\n const encryptedCredentials = await symmetricEncrypt({\n key: ctx.context.secret,\n data: JSON.stringify(credentials),\n });\n\n return {\n context: {\n ...ctx,\n jazzAuth: {\n accountID: jazzAuth.accountID,\n encryptedCredentials: encryptedCredentials,\n },\n },\n };\n }),\n },\n\n /**\n * For: Social / OAuth2 plugin\n * /callback is the endpoint that BetterAuth uses to authenticate the user coming from a social provider.\n * 1. Catch the state\n * 2. Find the verification value\n * 3. If the verification value contains a jazzAuth, inject into the context to have it in case of registration.\n */\n {\n matcher: (context) => {\n return (\n context.path.startsWith(\"/callback\") ||\n context.path.startsWith(\"/oauth2/callback\")\n );\n },\n handler: createAuthMiddleware(async (ctx) => {\n const state = ctx.query?.state || ctx.body?.state;\n\n const identifier = `jazz-auth-${state}`;\n\n const data =\n await ctx.context.internalAdapter.findVerificationValue(\n identifier,\n );\n\n // if not found, the social plugin will throw later anyway\n if (!data) {\n throw new APIError(404, {\n message: \"Verification not found\",\n });\n }\n\n const parsed = JSON.parse(data.value);\n\n if (parsed && \"jazzAuth\" in parsed) {\n return {\n context: {\n ...ctx,\n jazzAuth: parsed.jazzAuth,\n },\n };\n } else {\n throw new APIError(404, {\n message: \"JazzAuth not found in verification value\",\n });\n }\n }),\n },\n /**\n * For: Email OTP plugin\n * When the user sends an OTP, we try to find the jazzAuth.\n * If it isn't a sign-up, we expect to not find a verification value.\n */\n {\n matcher: (context) => {\n return context.path.startsWith(\"/sign-in/email-otp\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n const email = ctx.body.email;\n const identifier = `jazz-auth-sign-in-otp-${email}`;\n\n const data =\n await ctx.context.internalAdapter.findVerificationValue(\n identifier,\n );\n\n // if not found, it isn't a sign-up\n if (!data || data.expiresAt < new Date()) {\n return;\n }\n\n const parsed = JSON.parse(data.value);\n\n if (parsed && \"jazzAuth\" in parsed) {\n return {\n context: {\n ...ctx,\n jazzAuth: parsed.jazzAuth,\n },\n };\n } else {\n throw new APIError(500, {\n message: \"JazzAuth not found in verification value\",\n });\n }\n }),\n },\n ],\n after: [\n /**\n * This middleware is used to extract the jazzAuth from the user and return it in the response.\n * It is used in the following endpoints that return the user:\n * - /sign-up/email\n * - /sign-in/email\n * - /get-session\n */\n {\n matcher: (context) => {\n return (\n context.path.startsWith(\"/sign-up\") ||\n context.path.startsWith(\"/sign-in\") ||\n context.path.startsWith(\"/get-session\")\n );\n },\n handler: createAuthMiddleware({}, async (ctx) => {\n const returned = ctx.context.returned as any;\n if (!returned?.user?.id) {\n return;\n }\n const jazzAuth = await extractJazzAuth(returned.user.id, ctx);\n\n return ctx.json({\n ...returned,\n jazzAuth: jazzAuth,\n });\n }),\n },\n\n /**\n * For: Social / OAuth2 plugin\n * When the user sign-in via social, we create a verification value with the jazzAuth.\n */\n {\n matcher: (context) => {\n return context.path.startsWith(\"/sign-in/social\");\n },\n handler: createAuthMiddleware(async (ctx) => {\n if (!contextContainsJazzAuth(ctx)) {\n throw new APIError(500, {\n message: \"JazzAuth not found in context\",\n });\n }\n\n const returned = ctx.context.returned as { url: string };\n\n const url = new URL(returned.url);\n const state = url.searchParams.get(\"state\");\n\n const value = JSON.stringify({ jazzAuth: ctx.jazzAuth });\n const expiresAt = new Date();\n expiresAt.setMinutes(expiresAt.getMinutes() + 10);\n\n await ctx.context.internalAdapter.createVerificationValue({\n value,\n identifier: `jazz-auth-${state}`,\n expiresAt,\n });\n }),\n },\n ],\n },\n } satisfies JazzPlugin;\n};\n\nfunction contextContainsJazzAuth(ctx: unknown): ctx is {\n jazzAuth: {\n accountID: string;\n encryptedCredentials: string;\n };\n} {\n return !!ctx && typeof ctx === \"object\" && \"jazzAuth\" in ctx;\n}\n\nasync function extractJazzAuth(\n userId: string,\n ctx: MiddlewareContext<\n MiddlewareOptions,\n AuthContext & {\n returned?: unknown;\n responseHeaders?: Headers;\n }\n >,\n) {\n const user = await ctx.context.adapter.findOne<{\n accountID: string;\n encryptedCredentials: string;\n }>({\n model: ctx.context.tables.user!.modelName,\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: userId,\n },\n ],\n select: [\"accountID\", \"encryptedCredentials\"],\n });\n\n if (!user) {\n return;\n }\n\n const jazzAuth = JSON.parse(\n await symmetricDecrypt({\n key: ctx.context.secret,\n data: user.encryptedCredentials,\n }),\n );\n\n return jazzAuth;\n}\n"],"mappings":";AACA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB,wBAAwB;AACnD,SAA2B,4BAA4B;AAqChD,IAAM,aAA+B,MAAM;AAChD,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,QAAQ;AAAA,MACN,MAAM;AAAA,QACJ,QAAQ;AAAA,UACN,WAAW;AAAA,YACT,MAAM;AAAA,YACN,UAAU;AAAA,YACV,OAAO;AAAA,UACT;AAAA,UACA,sBAAsB;AAAA,YACpB,MAAM;AAAA,YACN,UAAU;AAAA,YACV,OAAO;AAAA,YACP,UAAU;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,OAAO;AACL,aAAO;AAAA,QACL,SAAS;AAAA,UACP,eAAe;AAAA,YACb,MAAM;AAAA,cACJ,QAAQ;AAAA,gBACN,QAAQ,OAAO,MAAM,YAAY;AAE/B,sBAAI,CAAC,wBAAwB,OAAO,GAAG;AACrC,0BAAM,IAAI,SAAS,KAAK;AAAA,sBACtB,SAAS;AAAA,oBACX,CAAC;AAAA,kBACH;AAEA,yBAAO;AAAA,oBACL,MAAM;AAAA,sBACJ,WAAW,QAAQ,SAAS;AAAA,sBAC5B,sBACE,QAAQ,SAAS;AAAA,oBACrB;AAAA,kBACF;AAAA,gBACF;AAAA,cACF;AAAA,YACF;AAAA,YACA,cAAc;AAAA,cACZ,QA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A,YAAY,aAAa,KAAK;AAAA,cAC9B;AAAA,YACF,CAAC;AAAA,UACH,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,wBAAwB,KAK/B;AACA,SAAO,CAAC,CAAC,OAAO,OAAO,QAAQ,YAAY,cAAc;AAC3D;AAEA,eAAe,gBACb,QACA,KAOA;AACA,QAAM,OAAO,MAAM,IAAI,QAAQ,QAAQ,QAGpC;AAAA,IACD,OAAO,IAAI,QAAQ,OAAO,KAAM;AAAA,IAChC,OAAO;AAAA,MACL;AAAA,QACE,OAAO;AAAA,QACP,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,aAAa,sBAAsB;AAAA,EAC9C,CAAC;AAED,MAAI,CAAC,MAAM;AACT;AAAA,EACF;AAEA,QAAM,WAAW,KAAK;AAAA,IACpB,MAAM,iBAAiB;AAAA,MACrB,KAAK,IAAI,QAAQ;AAAA,MACjB,MAAM,KAAK;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -4694,9 +4694,13 @@ function enrichCoMapSchema(schema, coValueClass) {
4694
4694
  }
4695
4695
  return coMapDefiner(pickedShape);
4696
4696
  },
4697
- partial: () => {
4697
+ partial: (keys) => {
4698
4698
  const partialShape = {};
4699
4699
  for (const [key, value] of Object.entries(coValueSchema.shape)) {
4700
+ if (keys && !keys[key]) {
4701
+ partialShape[key] = value;
4702
+ continue;
4703
+ }
4700
4704
  if (isAnyCoValueSchema2(value)) {
4701
4705
  partialShape[key] = coOptionalDefiner(value);
4702
4706
  } else {
@@ -5362,10 +5366,12 @@ var JazzContextManager = class {
5362
5366
  constructor(opts) {
5363
5367
  this.authSecretStorage = new AuthSecretStorage();
5364
5368
  this.keepContextOpen = false;
5369
+ this.authenticatingAccountID = null;
5365
5370
  this.logOut = async () => {
5366
5371
  if (!this.context || !this.props) {
5367
5372
  return;
5368
5373
  }
5374
+ this.authenticatingAccountID = null;
5369
5375
  await this.props.onLogOut?.();
5370
5376
  if (this.props.logOutReplacement) {
5371
5377
  await this.props.logOutReplacement();
@@ -5395,38 +5401,64 @@ var JazzContextManager = class {
5395
5401
  if (!this.props) {
5396
5402
  throw new Error("Props required");
5397
5403
  }
5398
- const prevContext = this.context;
5399
- const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
5400
- this.keepContextOpen = migratingAnonymousAccount;
5401
- await this.createContext(this.props, { credentials }).finally(() => {
5402
- this.keepContextOpen = false;
5403
- });
5404
- if (migratingAnonymousAccount) {
5405
- await this.handleAnonymousAccountMigration(prevContext);
5404
+ if (this.authenticatingAccountID && this.authenticatingAccountID === credentials.accountID) {
5405
+ console.info(
5406
+ "Authentication already in progress for account",
5407
+ credentials.accountID,
5408
+ "skipping duplicate request"
5409
+ );
5410
+ return;
5411
+ }
5412
+ if (this.authenticatingAccountID && this.authenticatingAccountID !== credentials.accountID) {
5413
+ throw new Error(
5414
+ `Authentication already in progress for different account (${this.authenticatingAccountID}), cannot authenticate ${credentials.accountID}`
5415
+ );
5416
+ }
5417
+ this.authenticatingAccountID = credentials.accountID;
5418
+ try {
5419
+ const prevContext = this.context;
5420
+ const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
5421
+ this.keepContextOpen = migratingAnonymousAccount;
5422
+ await this.createContext(this.props, { credentials }).finally(() => {
5423
+ this.keepContextOpen = false;
5424
+ });
5425
+ if (migratingAnonymousAccount) {
5426
+ await this.handleAnonymousAccountMigration(prevContext);
5427
+ }
5428
+ } finally {
5429
+ this.authenticatingAccountID = null;
5406
5430
  }
5407
5431
  };
5408
5432
  this.register = async (accountSecret, creationProps) => {
5409
5433
  if (!this.props) {
5410
5434
  throw new Error("Props required");
5411
5435
  }
5412
- const prevContext = this.context;
5413
- const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
5414
- this.keepContextOpen = migratingAnonymousAccount;
5415
- await this.createContext(this.props, {
5416
- newAccountProps: {
5417
- secret: accountSecret,
5418
- creationProps
5419
- }
5420
- }).finally(() => {
5421
- this.keepContextOpen = false;
5422
- });
5423
- if (migratingAnonymousAccount) {
5424
- await this.handleAnonymousAccountMigration(prevContext);
5436
+ if (this.authenticatingAccountID) {
5437
+ throw new Error("Authentication already in progress");
5425
5438
  }
5426
- if (this.context && "me" in this.context) {
5427
- return this.context.me.$jazz.id;
5439
+ this.authenticatingAccountID = "register";
5440
+ try {
5441
+ const prevContext = this.context;
5442
+ const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
5443
+ this.keepContextOpen = migratingAnonymousAccount;
5444
+ await this.createContext(this.props, {
5445
+ newAccountProps: {
5446
+ secret: accountSecret,
5447
+ creationProps
5448
+ }
5449
+ }).finally(() => {
5450
+ this.keepContextOpen = false;
5451
+ });
5452
+ if (migratingAnonymousAccount) {
5453
+ await this.handleAnonymousAccountMigration(prevContext);
5454
+ }
5455
+ if (this.context && "me" in this.context) {
5456
+ return this.context.me.$jazz.id;
5457
+ }
5458
+ throw new Error("The registration hasn't created a new account");
5459
+ } finally {
5460
+ this.authenticatingAccountID = null;
5428
5461
  }
5429
- throw new Error("The registration hasn't created a new account");
5430
5462
  };
5431
5463
  this.listeners = /* @__PURE__ */ new Set();
5432
5464
  this.subscribe = (callback) => {
@@ -5496,6 +5528,9 @@ var JazzContextManager = class {
5496
5528
  getAuthSecretStorage() {
5497
5529
  return this.authSecretStorage;
5498
5530
  }
5531
+ getAuthenticatingAccountID() {
5532
+ return this.authenticatingAccountID;
5533
+ }
5499
5534
  async handleAnonymousAccountMigration(prevContext) {
5500
5535
  if (!this.props) {
5501
5536
  throw new Error("Props required");
@@ -5907,4 +5942,4 @@ export {
5907
5942
  JazzContextManager
5908
5943
  };
5909
5944
  /* istanbul ignore file -- @preserve */
5910
- //# sourceMappingURL=chunk-CFAY3FMQ.js.map
5945
+ //# sourceMappingURL=chunk-RQHJFPIB.js.map