@terreno/syncdb 57.20.0 → 58.0.0-beta.1
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/CHANGELOG.md +93 -0
- package/README.md +7 -7
- package/dist/api/apiError.d.ts +43 -0
- package/dist/api/apiError.d.ts.map +1 -0
- package/dist/api/apiError.js +28 -0
- package/dist/api/apiError.js.map +1 -0
- package/dist/api/apiFetch.d.ts +44 -0
- package/dist/api/apiFetch.d.ts.map +1 -0
- package/dist/api/apiFetch.js +203 -0
- package/dist/api/apiFetch.js.map +1 -0
- package/dist/api/client.d.ts +70 -0
- package/dist/api/client.d.ts.map +1 -0
- package/dist/api/client.js +240 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/client.test.d.ts +2 -0
- package/dist/api/client.test.d.ts.map +1 -0
- package/dist/api/client.test.js +588 -0
- package/dist/api/client.test.js.map +1 -0
- package/dist/app/app.d.ts +13 -0
- package/dist/app/app.d.ts.map +1 -0
- package/dist/app/app.js +13 -0
- package/dist/app/app.js.map +1 -0
- package/dist/app/devConsoleLogger.d.ts +18 -0
- package/dist/app/devConsoleLogger.d.ts.map +1 -0
- package/dist/app/devConsoleLogger.js +147 -0
- package/dist/app/devConsoleLogger.js.map +1 -0
- package/dist/app/devConsoleLogger.test.d.ts +2 -0
- package/dist/app/devConsoleLogger.test.d.ts.map +1 -0
- package/dist/app/devConsoleLogger.test.js +202 -0
- package/dist/app/devConsoleLogger.test.js.map +1 -0
- package/dist/app/mcpTools.d.ts +32 -0
- package/dist/app/mcpTools.d.ts.map +1 -0
- package/dist/app/mcpTools.js +61 -0
- package/dist/app/mcpTools.js.map +1 -0
- package/dist/app/permissions.d.ts +26 -0
- package/dist/app/permissions.d.ts.map +1 -0
- package/dist/app/permissions.js +37 -0
- package/dist/app/permissions.js.map +1 -0
- package/dist/app/permissions.test.d.ts +2 -0
- package/dist/app/permissions.test.d.ts.map +1 -0
- package/dist/app/permissions.test.js +36 -0
- package/dist/app/permissions.test.js.map +1 -0
- package/dist/app/upgradeCheck.d.ts +46 -0
- package/dist/app/upgradeCheck.d.ts.map +1 -0
- package/dist/app/upgradeCheck.js +121 -0
- package/dist/app/upgradeCheck.js.map +1 -0
- package/dist/auth/SessionProvider.d.ts +40 -0
- package/dist/auth/SessionProvider.d.ts.map +1 -0
- package/dist/auth/SessionProvider.js +44 -0
- package/dist/auth/SessionProvider.js.map +1 -0
- package/dist/auth/SessionProvider.test.d.ts +2 -0
- package/dist/auth/SessionProvider.test.d.ts.map +1 -0
- package/dist/auth/SessionProvider.test.js +240 -0
- package/dist/auth/SessionProvider.test.js.map +1 -0
- package/dist/auth/TerrenoAccountSecurityScreen.d.ts +25 -0
- package/dist/auth/TerrenoAccountSecurityScreen.d.ts.map +1 -0
- package/dist/auth/TerrenoAccountSecurityScreen.js +21 -0
- package/dist/auth/TerrenoAccountSecurityScreen.js.map +1 -0
- package/dist/auth/TerrenoLoginScreen.d.ts +62 -0
- package/dist/auth/TerrenoLoginScreen.d.ts.map +1 -0
- package/dist/auth/TerrenoLoginScreen.js +45 -0
- package/dist/auth/TerrenoLoginScreen.js.map +1 -0
- package/dist/auth/auth.d.ts +36 -0
- package/dist/auth/auth.d.ts.map +1 -0
- package/dist/auth/auth.js +35 -0
- package/dist/auth/auth.js.map +1 -0
- package/dist/auth/betterAuthAdapter.d.ts +1 -1
- package/dist/auth/betterAuthClient.d.ts +276 -0
- package/dist/auth/betterAuthClient.d.ts.map +1 -0
- package/dist/auth/betterAuthClient.js +744 -0
- package/dist/auth/betterAuthClient.js.map +1 -0
- package/dist/auth/betterAuthClient.types.test.d.ts +2 -0
- package/dist/auth/betterAuthClient.types.test.d.ts.map +1 -0
- package/dist/auth/betterAuthClient.types.test.js +151 -0
- package/dist/auth/betterAuthClient.types.test.js.map +1 -0
- package/dist/auth/betterAuthClientRegistry.d.ts +51 -0
- package/dist/auth/betterAuthClientRegistry.d.ts.map +1 -0
- package/dist/auth/betterAuthClientRegistry.js +69 -0
- package/dist/auth/betterAuthClientRegistry.js.map +1 -0
- package/dist/auth/betterAuthClientRegistry.test.d.ts +2 -0
- package/dist/auth/betterAuthClientRegistry.test.d.ts.map +1 -0
- package/dist/auth/betterAuthClientRegistry.test.js +91 -0
- package/dist/auth/betterAuthClientRegistry.test.js.map +1 -0
- package/dist/auth/betterAuthTypes.d.ts +172 -0
- package/dist/auth/betterAuthTypes.d.ts.map +1 -0
- package/dist/auth/betterAuthTypes.js +7 -0
- package/dist/auth/betterAuthTypes.js.map +1 -0
- package/dist/auth/jwtAuthAdapter.d.ts +102 -0
- package/dist/auth/jwtAuthAdapter.d.ts.map +1 -0
- package/dist/auth/jwtAuthAdapter.js +282 -0
- package/dist/auth/jwtAuthAdapter.js.map +1 -0
- package/dist/auth/jwtAuthAdapter.test.d.ts +2 -0
- package/dist/auth/jwtAuthAdapter.test.d.ts.map +1 -0
- package/dist/auth/jwtAuthAdapter.test.js +614 -0
- package/dist/auth/jwtAuthAdapter.test.js.map +1 -0
- package/dist/auth/loginErrors.d.ts +75 -0
- package/dist/auth/loginErrors.d.ts.map +1 -0
- package/dist/auth/loginErrors.js +154 -0
- package/dist/auth/loginErrors.js.map +1 -0
- package/dist/auth/loginErrors.test.d.ts +2 -0
- package/dist/auth/loginErrors.test.d.ts.map +1 -0
- package/dist/auth/loginErrors.test.js +70 -0
- package/dist/auth/loginErrors.test.js.map +1 -0
- package/dist/auth/ownEntry.d.ts +8 -0
- package/dist/auth/ownEntry.d.ts.map +1 -0
- package/dist/auth/ownEntry.js +13 -0
- package/dist/auth/ownEntry.js.map +1 -0
- package/dist/auth/ownEntry.test.d.ts +2 -0
- package/dist/auth/ownEntry.test.d.ts.map +1 -0
- package/dist/auth/ownEntry.test.js +18 -0
- package/dist/auth/ownEntry.test.js.map +1 -0
- package/dist/auth/platform.d.ts +3 -0
- package/dist/auth/platform.d.ts.map +1 -0
- package/dist/auth/platform.js +4 -0
- package/dist/auth/platform.js.map +1 -0
- package/dist/auth/rememberedAccounts.d.ts +126 -0
- package/dist/auth/rememberedAccounts.d.ts.map +1 -0
- package/dist/auth/rememberedAccounts.js +399 -0
- package/dist/auth/rememberedAccounts.js.map +1 -0
- package/dist/auth/rememberedAccounts.test.d.ts +2 -0
- package/dist/auth/rememberedAccounts.test.d.ts.map +1 -0
- package/dist/auth/rememberedAccounts.test.js +676 -0
- package/dist/auth/rememberedAccounts.test.js.map +1 -0
- package/dist/auth/session.d.ts +118 -0
- package/dist/auth/session.d.ts.map +1 -0
- package/dist/auth/session.js +370 -0
- package/dist/auth/session.js.map +1 -0
- package/dist/auth/session.test.d.ts +2 -0
- package/dist/auth/session.test.d.ts.map +1 -0
- package/dist/auth/session.test.js +825 -0
- package/dist/auth/session.test.js.map +1 -0
- package/dist/auth/tokenExpiry.d.ts +70 -0
- package/dist/auth/tokenExpiry.d.ts.map +1 -0
- package/dist/auth/tokenExpiry.js +123 -0
- package/dist/auth/tokenExpiry.js.map +1 -0
- package/dist/auth/types.d.ts +1 -1
- package/dist/auth/types.js +1 -1
- package/dist/auth/useAccountSecurity.d.ts +183 -0
- package/dist/auth/useAccountSecurity.d.ts.map +1 -0
- package/dist/auth/useAccountSecurity.js +399 -0
- package/dist/auth/useAccountSecurity.js.map +1 -0
- package/dist/auth/useAccountSecurity.types.test.d.ts +2 -0
- package/dist/auth/useAccountSecurity.types.test.d.ts.map +1 -0
- package/dist/auth/useAccountSecurity.types.test.js +21 -0
- package/dist/auth/useAccountSecurity.types.test.js.map +1 -0
- package/dist/auth/useAuthMethods.d.ts +67 -0
- package/dist/auth/useAuthMethods.d.ts.map +1 -0
- package/dist/auth/useAuthMethods.js +77 -0
- package/dist/auth/useAuthMethods.js.map +1 -0
- package/dist/auth/useAuthMethods.test.d.ts +2 -0
- package/dist/auth/useAuthMethods.test.d.ts.map +1 -0
- package/dist/auth/useAuthMethods.test.js +145 -0
- package/dist/auth/useAuthMethods.test.js.map +1 -0
- package/dist/auth/useJwtAuth.d.ts +31 -0
- package/dist/auth/useJwtAuth.d.ts.map +1 -0
- package/dist/auth/useJwtAuth.js +58 -0
- package/dist/auth/useJwtAuth.js.map +1 -0
- package/dist/auth/useJwtAuth.test.d.ts +2 -0
- package/dist/auth/useJwtAuth.test.d.ts.map +1 -0
- package/dist/auth/useJwtAuth.test.js +165 -0
- package/dist/auth/useJwtAuth.test.js.map +1 -0
- package/dist/auth/useLoginController.d.ts +248 -0
- package/dist/auth/useLoginController.d.ts.map +1 -0
- package/dist/auth/useLoginController.js +671 -0
- package/dist/auth/useLoginController.js.map +1 -0
- package/dist/auth/useLoginController.types.test.d.ts +2 -0
- package/dist/auth/useLoginController.types.test.d.ts.map +1 -0
- package/dist/auth/useLoginController.types.test.js +19 -0
- package/dist/auth/useLoginController.types.test.js.map +1 -0
- package/dist/buildNumber.d.ts +34 -0
- package/dist/buildNumber.d.ts.map +1 -0
- package/dist/buildNumber.js +62 -0
- package/dist/buildNumber.js.map +1 -0
- package/dist/buildNumber.test.d.ts +2 -0
- package/dist/buildNumber.test.d.ts.map +1 -0
- package/dist/buildNumber.test.js +114 -0
- package/dist/buildNumber.test.js.map +1 -0
- package/dist/client.d.ts +10 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +237 -184
- package/dist/client.js.map +1 -1
- package/dist/client.socketEvents.test.d.ts +2 -0
- package/dist/client.socketEvents.test.d.ts.map +1 -0
- package/dist/client.socketEvents.test.js +64 -0
- package/dist/client.socketEvents.test.js.map +1 -0
- package/dist/client.test.js +60 -1
- package/dist/client.test.js.map +1 -1
- package/dist/codegen/cli.js +23 -12
- package/dist/codegen/cli.js.map +1 -1
- package/dist/codegen/cli.test.js +57 -0
- package/dist/codegen/cli.test.js.map +1 -1
- package/dist/codegen/discoverCollections.d.ts.map +1 -1
- package/dist/codegen/discoverCollections.js +4 -0
- package/dist/codegen/discoverCollections.js.map +1 -1
- package/dist/codegen/discoverOperations.d.ts +11 -0
- package/dist/codegen/discoverOperations.d.ts.map +1 -0
- package/dist/codegen/discoverOperations.js +135 -0
- package/dist/codegen/discoverOperations.js.map +1 -0
- package/dist/codegen/emitApi.d.ts +8 -0
- package/dist/codegen/emitApi.d.ts.map +1 -0
- package/dist/codegen/emitApi.js +312 -0
- package/dist/codegen/emitApi.js.map +1 -0
- package/dist/codegen/emitApi.test.d.ts +2 -0
- package/dist/codegen/emitApi.test.d.ts.map +1 -0
- package/dist/codegen/emitApi.test.js +360 -0
- package/dist/codegen/emitApi.test.js.map +1 -0
- package/dist/codegen/emitSdk.js +2 -2
- package/dist/codegen/generate.d.ts +6 -1
- package/dist/codegen/generate.d.ts.map +1 -1
- package/dist/codegen/generate.js +18 -0
- package/dist/codegen/generate.js.map +1 -1
- package/dist/codegen/generate.test.js +53 -1
- package/dist/codegen/generate.test.js.map +1 -1
- package/dist/codegen/hookNames.d.ts +11 -0
- package/dist/codegen/hookNames.d.ts.map +1 -1
- package/dist/codegen/hookNames.js +23 -0
- package/dist/codegen/hookNames.js.map +1 -1
- package/dist/codegen/safeIdentifiers.d.ts +5 -1
- package/dist/codegen/safeIdentifiers.d.ts.map +1 -1
- package/dist/codegen/safeIdentifiers.js +7 -2
- package/dist/codegen/safeIdentifiers.js.map +1 -1
- package/dist/codegen/safeIdentifiers.test.js +9 -0
- package/dist/codegen/safeIdentifiers.test.js.map +1 -1
- package/dist/codegen/types.d.ts +46 -1
- package/dist/codegen/types.d.ts.map +1 -1
- package/dist/config/baseUrl.d.ts +13 -0
- package/dist/config/baseUrl.d.ts.map +1 -0
- package/dist/config/baseUrl.js +49 -0
- package/dist/config/baseUrl.js.map +1 -0
- package/dist/config/baseUrl.test.d.ts +2 -0
- package/dist/config/baseUrl.test.d.ts.map +1 -0
- package/dist/config/baseUrl.test.js +42 -0
- package/dist/config/baseUrl.test.js.map +1 -0
- package/dist/config/resolveBaseUrls.d.ts +53 -0
- package/dist/config/resolveBaseUrls.d.ts.map +1 -0
- package/dist/config/resolveBaseUrls.js +80 -0
- package/dist/config/resolveBaseUrls.js.map +1 -0
- package/dist/config/resolveBaseUrls.test.d.ts +2 -0
- package/dist/config/resolveBaseUrls.test.d.ts.map +1 -0
- package/dist/config/resolveBaseUrls.test.js +265 -0
- package/dist/config/resolveBaseUrls.test.js.map +1 -0
- package/dist/crypto/keyProviders.d.ts +2 -2
- package/dist/crypto/keyProviders.d.ts.map +1 -1
- package/dist/crypto/keyProviders.js +15 -4
- package/dist/crypto/keyProviders.js.map +1 -1
- package/dist/crypto/keyProviders.test.js +19 -0
- package/dist/crypto/keyProviders.test.js.map +1 -1
- package/dist/crypto/types.d.ts +5 -0
- package/dist/crypto/types.d.ts.map +1 -1
- package/dist/flags/flagTestServer.d.ts +19 -0
- package/dist/flags/flagTestServer.d.ts.map +1 -0
- package/dist/flags/flagTestServer.js +58 -0
- package/dist/flags/flagTestServer.js.map +1 -0
- package/dist/flags/useFeatureFlags.d.ts +30 -0
- package/dist/flags/useFeatureFlags.d.ts.map +1 -0
- package/dist/flags/useFeatureFlags.js +83 -0
- package/dist/flags/useFeatureFlags.js.map +1 -0
- package/dist/flags/useFeatureFlags.test.d.ts +2 -0
- package/dist/flags/useFeatureFlags.test.d.ts.map +1 -0
- package/dist/flags/useFeatureFlags.test.js +116 -0
- package/dist/flags/useFeatureFlags.test.js.map +1 -0
- package/dist/flags/useTerrenoFeatureFlags.d.ts +50 -0
- package/dist/flags/useTerrenoFeatureFlags.d.ts.map +1 -0
- package/dist/flags/useTerrenoFeatureFlags.js +125 -0
- package/dist/flags/useTerrenoFeatureFlags.js.map +1 -0
- package/dist/flags/useTerrenoFeatureFlags.test.d.ts +2 -0
- package/dist/flags/useTerrenoFeatureFlags.test.d.ts.map +1 -0
- package/dist/flags/useTerrenoFeatureFlags.test.js +259 -0
- package/dist/flags/useTerrenoFeatureFlags.test.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/isolated/TerrenoAccountSecurityScreen.isolated.d.ts +2 -0
- package/dist/isolated/TerrenoAccountSecurityScreen.isolated.d.ts.map +1 -0
- package/dist/isolated/TerrenoAccountSecurityScreen.isolated.js +94 -0
- package/dist/isolated/TerrenoAccountSecurityScreen.isolated.js.map +1 -0
- package/dist/isolated/TerrenoLoginScreen.isolated.d.ts +2 -0
- package/dist/isolated/TerrenoLoginScreen.isolated.d.ts.map +1 -0
- package/dist/isolated/TerrenoLoginScreen.isolated.js +183 -0
- package/dist/isolated/TerrenoLoginScreen.isolated.js.map +1 -0
- package/dist/isolated/betterAuthClient.isolated.d.ts +2 -0
- package/dist/isolated/betterAuthClient.isolated.d.ts.map +1 -0
- package/dist/isolated/betterAuthClient.isolated.js +1734 -0
- package/dist/isolated/betterAuthClient.isolated.js.map +1 -0
- package/dist/isolated/betterAuthClient.native.isolated.d.ts +2 -0
- package/dist/isolated/betterAuthClient.native.isolated.d.ts.map +1 -0
- package/dist/isolated/betterAuthClient.native.isolated.js +153 -0
- package/dist/isolated/betterAuthClient.native.isolated.js.map +1 -0
- package/dist/isolated/mcpTools.isolated.d.ts +2 -0
- package/dist/isolated/mcpTools.isolated.d.ts.map +1 -0
- package/dist/isolated/mcpTools.isolated.js +197 -0
- package/dist/isolated/mcpTools.isolated.js.map +1 -0
- package/dist/isolated/rememberedAccounts.native.isolated.d.ts +2 -0
- package/dist/isolated/rememberedAccounts.native.isolated.d.ts.map +1 -0
- package/dist/isolated/rememberedAccounts.native.isolated.js +50 -0
- package/dist/isolated/rememberedAccounts.native.isolated.js.map +1 -0
- package/dist/isolated/sessionLogout.isolated.d.ts +2 -0
- package/dist/isolated/sessionLogout.isolated.d.ts.map +1 -0
- package/dist/isolated/sessionLogout.isolated.js +133 -0
- package/dist/isolated/sessionLogout.isolated.js.map +1 -0
- package/dist/isolated/tokenExpiry.isolated.d.ts +2 -0
- package/dist/isolated/tokenExpiry.isolated.d.ts.map +1 -0
- package/dist/isolated/tokenExpiry.isolated.js +232 -0
- package/dist/isolated/tokenExpiry.isolated.js.map +1 -0
- package/dist/isolated/upgradeCheck.isolated.d.ts +2 -0
- package/dist/isolated/upgradeCheck.isolated.d.ts.map +1 -0
- package/dist/isolated/upgradeCheck.isolated.js +241 -0
- package/dist/isolated/upgradeCheck.isolated.js.map +1 -0
- package/dist/isolated/useAccountSecurity.isolated.d.ts +2 -0
- package/dist/isolated/useAccountSecurity.isolated.d.ts.map +1 -0
- package/dist/isolated/useAccountSecurity.isolated.js +851 -0
- package/dist/isolated/useAccountSecurity.isolated.js.map +1 -0
- package/dist/isolated/useAccountSecurity.native.isolated.d.ts +2 -0
- package/dist/isolated/useAccountSecurity.native.isolated.d.ts.map +1 -0
- package/dist/isolated/useAccountSecurity.native.isolated.js +52 -0
- package/dist/isolated/useAccountSecurity.native.isolated.js.map +1 -0
- package/dist/isolated/useLoginController.isolated.d.ts +2 -0
- package/dist/isolated/useLoginController.isolated.d.ts.map +1 -0
- package/dist/isolated/useLoginController.isolated.js +1116 -0
- package/dist/isolated/useLoginController.isolated.js.map +1 -0
- package/dist/persisters/defaultPersisterFactory.native.d.ts.map +1 -1
- package/dist/persisters/defaultPersisterFactory.native.js +2 -0
- package/dist/persisters/defaultPersisterFactory.native.js.map +1 -1
- package/dist/persisters/encryptedIndexedDbPersister.d.ts.map +1 -1
- package/dist/persisters/encryptedIndexedDbPersister.js +3 -0
- package/dist/persisters/encryptedIndexedDbPersister.js.map +1 -1
- package/dist/persisters/types.d.ts +6 -0
- package/dist/persisters/types.d.ts.map +1 -1
- package/dist/query/queryWindows.js +2 -2
- package/dist/query/queryWindows.js.map +1 -1
- package/dist/react/apiHooks.d.ts +87 -0
- package/dist/react/apiHooks.d.ts.map +1 -0
- package/dist/react/apiHooks.js +195 -0
- package/dist/react/apiHooks.js.map +1 -0
- package/dist/react/apiHooks.test.d.ts +2 -0
- package/dist/react/apiHooks.test.d.ts.map +1 -0
- package/dist/react/apiHooks.test.js +366 -0
- package/dist/react/apiHooks.test.js.map +1 -0
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +2 -0
- package/dist/react/index.js.map +1 -1
- package/dist/react/provider.d.ts +2 -0
- package/dist/react/provider.d.ts.map +1 -1
- package/dist/react/provider.js +2 -0
- package/dist/react/provider.js.map +1 -1
- package/dist/react/useSocketEvent.d.ts +27 -0
- package/dist/react/useSocketEvent.d.ts.map +1 -0
- package/dist/react/useSocketEvent.js +36 -0
- package/dist/react/useSocketEvent.js.map +1 -0
- package/dist/react/useSocketEvent.test.d.ts +2 -0
- package/dist/react/useSocketEvent.test.d.ts.map +1 -0
- package/dist/react/useSocketEvent.test.js +76 -0
- package/dist/react/useSocketEvent.test.js.map +1 -0
- package/dist/sync/replayCoordinator.js +1 -1
- package/dist/sync/replayCoordinator.js.map +1 -1
- package/dist/sync/socketTransport.d.ts.map +1 -1
- package/dist/sync/socketTransport.js +14 -1
- package/dist/sync/socketTransport.js.map +1 -1
- package/dist/sync/socketTransport.test.js +42 -0
- package/dist/sync/socketTransport.test.js.map +1 -1
- package/dist/sync/transport.d.ts +9 -0
- package/dist/sync/transport.d.ts.map +1 -1
- package/dist/sync/transport.js +13 -0
- package/dist/sync/transport.js.map +1 -1
- package/dist/testing/fakeTransport.d.ts +5 -1
- package/dist/testing/fakeTransport.d.ts.map +1 -1
- package/dist/testing/fakeTransport.js +26 -0
- package/dist/testing/fakeTransport.js.map +1 -1
- package/dist/testing/fakeTransport.test.js +15 -0
- package/dist/testing/fakeTransport.test.js.map +1 -1
- package/package.json +96 -8
- package/src/api/apiError.ts +47 -0
- package/src/api/apiFetch.ts +245 -0
- package/src/api/client.test.ts +711 -0
- package/src/api/client.ts +367 -0
- package/src/app/app.ts +30 -0
- package/src/app/devConsoleLogger.test.ts +246 -0
- package/src/app/devConsoleLogger.ts +173 -0
- package/src/app/mcpTools.ts +101 -0
- package/src/app/permissions.test.ts +44 -0
- package/src/app/permissions.ts +58 -0
- package/src/app/upgradeCheck.ts +177 -0
- package/src/auth/SessionProvider.test.tsx +286 -0
- package/src/auth/SessionProvider.tsx +87 -0
- package/src/auth/TerrenoAccountSecurityScreen.tsx +56 -0
- package/src/auth/TerrenoLoginScreen.tsx +131 -0
- package/src/auth/auth.ts +117 -0
- package/src/auth/betterAuthAdapter.ts +1 -1
- package/src/auth/betterAuthClient.ts +997 -0
- package/src/auth/betterAuthClient.types.test.ts +197 -0
- package/src/auth/betterAuthClientRegistry.test.ts +114 -0
- package/src/auth/betterAuthClientRegistry.ts +99 -0
- package/src/auth/betterAuthTypes.ts +189 -0
- package/src/auth/jwtAuthAdapter.test.ts +754 -0
- package/src/auth/jwtAuthAdapter.ts +420 -0
- package/src/auth/loginErrors.test.ts +97 -0
- package/src/auth/loginErrors.ts +249 -0
- package/src/auth/ownEntry.test.ts +22 -0
- package/src/auth/ownEntry.ts +15 -0
- package/src/auth/platform.ts +4 -0
- package/src/auth/rememberedAccounts.test.ts +844 -0
- package/src/auth/rememberedAccounts.ts +568 -0
- package/src/auth/session.test.ts +976 -0
- package/src/auth/session.ts +509 -0
- package/src/auth/tokenExpiry.ts +185 -0
- package/src/auth/types.ts +1 -1
- package/src/auth/useAccountSecurity.ts +678 -0
- package/src/auth/useAccountSecurity.types.test.ts +28 -0
- package/src/auth/useAuthMethods.test.ts +181 -0
- package/src/auth/useAuthMethods.ts +137 -0
- package/src/auth/useJwtAuth.test.tsx +202 -0
- package/src/auth/useJwtAuth.ts +102 -0
- package/src/auth/useLoginController.ts +1038 -0
- package/src/auth/useLoginController.types.test.ts +26 -0
- package/src/buildNumber.test.ts +139 -0
- package/src/buildNumber.ts +75 -0
- package/src/client.socketEvents.test.ts +77 -0
- package/src/client.test.ts +73 -1
- package/src/client.ts +87 -18
- package/src/codegen/cli.test.ts +66 -0
- package/src/codegen/cli.ts +23 -12
- package/src/codegen/discoverCollections.ts +4 -0
- package/src/codegen/discoverOperations.ts +172 -0
- package/src/codegen/emitApi.test.tsx +445 -0
- package/src/codegen/emitApi.ts +396 -0
- package/src/codegen/emitSdk.ts +2 -2
- package/src/codegen/fixtures/openapi.api.json +840 -0
- package/src/codegen/generate.test.ts +54 -1
- package/src/codegen/generate.ts +20 -1
- package/src/codegen/hookNames.ts +35 -0
- package/src/codegen/safeIdentifiers.test.ts +20 -0
- package/src/codegen/safeIdentifiers.ts +7 -2
- package/src/codegen/types.ts +45 -1
- package/src/config/baseUrl.test.ts +53 -0
- package/src/config/baseUrl.ts +68 -0
- package/src/config/resolveBaseUrls.test.ts +308 -0
- package/src/config/resolveBaseUrls.ts +118 -0
- package/src/crypto/keyProviders.test.ts +23 -0
- package/src/crypto/keyProviders.ts +15 -4
- package/src/crypto/types.ts +5 -0
- package/src/flags/flagTestServer.ts +77 -0
- package/src/flags/useFeatureFlags.test.tsx +146 -0
- package/src/flags/useFeatureFlags.ts +130 -0
- package/src/flags/useTerrenoFeatureFlags.test.tsx +329 -0
- package/src/flags/useTerrenoFeatureFlags.ts +188 -0
- package/src/index.ts +2 -1
- package/src/isolated/TerrenoAccountSecurityScreen.isolated.tsx +123 -0
- package/src/isolated/TerrenoLoginScreen.isolated.tsx +256 -0
- package/src/isolated/betterAuthClient.isolated.ts +2198 -0
- package/src/isolated/betterAuthClient.native.isolated.ts +173 -0
- package/src/isolated/mcpTools.isolated.ts +259 -0
- package/src/isolated/rememberedAccounts.native.isolated.ts +63 -0
- package/src/isolated/sessionLogout.isolated.ts +152 -0
- package/src/isolated/tokenExpiry.isolated.ts +271 -0
- package/src/isolated/upgradeCheck.isolated.tsx +321 -0
- package/src/isolated/useAccountSecurity.isolated.ts +1089 -0
- package/src/isolated/useAccountSecurity.native.isolated.ts +61 -0
- package/src/isolated/useLoginController.isolated.ts +1384 -0
- package/src/persisters/defaultPersisterFactory.native.ts +7 -1
- package/src/persisters/encryptedIndexedDbPersister.ts +3 -0
- package/src/persisters/types.ts +6 -0
- package/src/query/queryWindows.ts +2 -2
- package/src/react/apiHooks.test.tsx +473 -0
- package/src/react/apiHooks.tsx +336 -0
- package/src/react/index.ts +2 -0
- package/src/react/provider.tsx +3 -0
- package/src/react/useSocketEvent.test.tsx +96 -0
- package/src/react/useSocketEvent.ts +59 -0
- package/src/sync/replayCoordinator.ts +1 -1
- package/src/sync/socketTransport.test.ts +49 -0
- package/src/sync/socketTransport.ts +15 -0
- package/src/sync/transport.ts +25 -0
- package/src/testing/fakeTransport.test.ts +18 -0
- package/src/testing/fakeTransport.ts +36 -5
|
@@ -0,0 +1,997 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Better Auth client factory for React Native/Expo applications.
|
|
3
|
+
*
|
|
4
|
+
* Provides a configured Better Auth client with Expo-specific storage
|
|
5
|
+
* and deep linking support.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {expoClient} from "@better-auth/expo/client";
|
|
9
|
+
import {passkeyClient} from "@better-auth/passkey/client";
|
|
10
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
11
|
+
import type {BetterAuthClientPlugin} from "better-auth/client";
|
|
12
|
+
import {
|
|
13
|
+
lastLoginMethodClient,
|
|
14
|
+
multiSessionClient,
|
|
15
|
+
oneTimeTokenClient,
|
|
16
|
+
twoFactorClient,
|
|
17
|
+
} from "better-auth/client/plugins";
|
|
18
|
+
import {createAuthClient, type ReactAuthClient} from "better-auth/react";
|
|
19
|
+
import * as SecureStore from "expo-secure-store";
|
|
20
|
+
import {
|
|
21
|
+
bearerTokenKey,
|
|
22
|
+
DEFAULT_STORAGE_PREFIX,
|
|
23
|
+
getBetterAuthBearerToken,
|
|
24
|
+
type HandoffClientConfig,
|
|
25
|
+
handoffClients,
|
|
26
|
+
resolveBearerStorage,
|
|
27
|
+
} from "./betterAuthClientRegistry";
|
|
28
|
+
import type {
|
|
29
|
+
BetterAuthBearerStorage,
|
|
30
|
+
BetterAuthClientConfig,
|
|
31
|
+
BetterAuthClientFeatures,
|
|
32
|
+
} from "./betterAuthTypes";
|
|
33
|
+
import {IsWeb} from "./platform";
|
|
34
|
+
|
|
35
|
+
export {getBetterAuthBearerToken, getBetterAuthClientWebAuth} from "./betterAuthClientRegistry";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Storage adapter interface matching what Better Auth expects.
|
|
39
|
+
*/
|
|
40
|
+
export interface StorageAdapter {
|
|
41
|
+
setItem: (key: string, value: string) => void | Promise<void>;
|
|
42
|
+
getItem: (key: string) => string | null | Promise<string | null>;
|
|
43
|
+
removeItem?: (key: string) => void | Promise<void>;
|
|
44
|
+
/** Async read; `@better-auth/expo` 1.7+ reads and writes its jar and session cache through it. */
|
|
45
|
+
getItemAsync?: (key: string) => Promise<string | null>;
|
|
46
|
+
/** Async write; see `getItemAsync`. */
|
|
47
|
+
setItemAsync?: (key: string, value: string) => Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type ExpoClientStorage = NonNullable<Parameters<typeof expoClient>[0]["storage"]>;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The part of the `@better-auth/expo` plugin that shapes the client type: its `getCookie`
|
|
54
|
+
* action. Typing the plugin as the generic `BetterAuthClientPlugin` instead collapses the
|
|
55
|
+
* inferred client so `getSession` / `signOut` disappear from its type.
|
|
56
|
+
*/
|
|
57
|
+
export interface ExpoAuthClientPlugin {
|
|
58
|
+
id: "expo";
|
|
59
|
+
getActions: () => {getCookie: () => string};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* True in a browser (react-native-web), false on iOS/Android. Evaluated per call (not at
|
|
64
|
+
* import) so syncdb never imports react-native and tests can flip it with a `document` stub.
|
|
65
|
+
*/
|
|
66
|
+
const detectIsWeb = (): boolean => typeof document !== "undefined";
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Storage adapter for Better Auth that works on both web and native.
|
|
70
|
+
* Uses SecureStore on native platforms and AsyncStorage on web.
|
|
71
|
+
*
|
|
72
|
+
* The native branch must be **synchronous**: `@better-auth/expo`'s client plugin reads the
|
|
73
|
+
* cookie jar inline (`getCookie(storage.getItem(name) || "{}")` followed by `JSON.parse`)
|
|
74
|
+
* while building request headers, and it sets `credentials: "omit"` on native so that
|
|
75
|
+
* stored jar is the only way a session token reaches the server. A promise-returning
|
|
76
|
+
* `getItem` fails the parse, yielding an empty jar and unauthenticated requests.
|
|
77
|
+
* `expo-secure-store` exposes sync `getItem`/`setItem` alongside the `*Async` variants.
|
|
78
|
+
* `@better-auth/expo` 1.7 also calls the async pair (`getItemAsync`/`setItemAsync`) on its
|
|
79
|
+
* serialized read/write path, so the native adapter provides both.
|
|
80
|
+
*
|
|
81
|
+
* The web branch stays async: the plugin short-circuits on web (`if (isWeb) return`) and
|
|
82
|
+
* lets the browser manage cookies, so it never reads this adapter there.
|
|
83
|
+
*
|
|
84
|
+
* `isWeb` is exposed as a parameter so the adapter can be unit tested
|
|
85
|
+
* without having to re-load the module for each platform.
|
|
86
|
+
*/
|
|
87
|
+
export const createStorageAdapter = (isWeb: boolean = detectIsWeb()): StorageAdapter => {
|
|
88
|
+
if (isWeb) {
|
|
89
|
+
return {
|
|
90
|
+
getItem: (key: string): Promise<string | null> => {
|
|
91
|
+
if (typeof window !== "undefined") {
|
|
92
|
+
return AsyncStorage.getItem(key);
|
|
93
|
+
}
|
|
94
|
+
return Promise.resolve(null);
|
|
95
|
+
},
|
|
96
|
+
removeItem: (key: string): Promise<void> => {
|
|
97
|
+
if (typeof window !== "undefined") {
|
|
98
|
+
return AsyncStorage.removeItem(key);
|
|
99
|
+
}
|
|
100
|
+
return Promise.resolve();
|
|
101
|
+
},
|
|
102
|
+
setItem: (key: string, value: string): Promise<void> => {
|
|
103
|
+
if (typeof window !== "undefined") {
|
|
104
|
+
return AsyncStorage.setItem(key, value);
|
|
105
|
+
}
|
|
106
|
+
return Promise.resolve();
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Native platform - use SecureStore's synchronous API (see note above).
|
|
112
|
+
return {
|
|
113
|
+
getItem: (key: string) => SecureStore.getItem(key),
|
|
114
|
+
getItemAsync: (key: string) => SecureStore.getItemAsync(key),
|
|
115
|
+
removeItem: (key: string) => SecureStore.deleteItemAsync(key),
|
|
116
|
+
setItem: (key: string, value: string) => SecureStore.setItem(key, value),
|
|
117
|
+
setItemAsync: (key: string, value: string) => SecureStore.setItemAsync(key, value),
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Drops cookie-jar entries that `@better-auth/expo` cannot read.
|
|
123
|
+
*
|
|
124
|
+
* The plugin keeps its jar as `{[name]: {value, expires}}` and reads it with
|
|
125
|
+
* `Object.entries(jar).reduce((acc, [name, cookie]) => cookie.expires ? ... )`. That property
|
|
126
|
+
* access throws on any entry whose value is not an object, and it runs inside the plugin's
|
|
127
|
+
* `init()` hook, ahead of *every* native request. One malformed entry therefore makes all
|
|
128
|
+
* requests throw before a socket is opened - sign-in included, so the app can never write a
|
|
129
|
+
* good jar over the bad one and stays permanently unable to reach the API. Discarding the
|
|
130
|
+
* unreadable entries degrades to "signed out", which signing in again recovers from.
|
|
131
|
+
*/
|
|
132
|
+
export const repairCookieJar = (stored: string | null): string | null => {
|
|
133
|
+
if (!stored) {
|
|
134
|
+
return stored;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
let parsed: unknown;
|
|
138
|
+
try {
|
|
139
|
+
parsed = JSON.parse(stored);
|
|
140
|
+
} catch {
|
|
141
|
+
// The plugin already tolerates unparseable jars by falling back to an empty one.
|
|
142
|
+
return stored;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// A non-object jar (including the literal `null`) makes the plugin's `Object.entries` throw.
|
|
146
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const entries = Object.entries(parsed);
|
|
151
|
+
const readable = entries.filter(([, cookie]) => typeof cookie === "object" && cookie !== null);
|
|
152
|
+
if (readable.length === entries.length) {
|
|
153
|
+
return stored;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
console.warn(
|
|
157
|
+
`[terreno/syncdb] Discarded ${entries.length - readable.length} unreadable Better Auth cookie ` +
|
|
158
|
+
"entry/entries; sign in again to restore the session."
|
|
159
|
+
);
|
|
160
|
+
return JSON.stringify(Object.fromEntries(readable));
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Wraps a storage adapter so reads of the Better Auth cookie jar are repaired first. Only the
|
|
165
|
+
* jar key is touched, because the plugin stores unrelated shapes under its other keys (the
|
|
166
|
+
* cached session payload holds plain strings and numbers, which `repairCookieJar` would strip).
|
|
167
|
+
*/
|
|
168
|
+
export const withCookieJarRepair = ({
|
|
169
|
+
cookieJarKey,
|
|
170
|
+
storage,
|
|
171
|
+
}: {
|
|
172
|
+
cookieJarKey: string;
|
|
173
|
+
storage: StorageAdapter;
|
|
174
|
+
}): StorageAdapter => ({
|
|
175
|
+
...storage,
|
|
176
|
+
getItem: (key: string): string | null | Promise<string | null> => {
|
|
177
|
+
const stored = storage.getItem(key);
|
|
178
|
+
if (key !== cookieJarKey) {
|
|
179
|
+
return stored;
|
|
180
|
+
}
|
|
181
|
+
if (stored instanceof Promise) {
|
|
182
|
+
return stored.then(repairCookieJar);
|
|
183
|
+
}
|
|
184
|
+
return repairCookieJar(stored);
|
|
185
|
+
},
|
|
186
|
+
// The 1.7 plugin reads through the async path too, so the jar is repaired there as well.
|
|
187
|
+
...(storage.getItemAsync
|
|
188
|
+
? {
|
|
189
|
+
getItemAsync: async (key: string): Promise<string | null> => {
|
|
190
|
+
const stored = await (
|
|
191
|
+
storage.getItemAsync as NonNullable<StorageAdapter["getItemAsync"]>
|
|
192
|
+
)(key);
|
|
193
|
+
return key === cookieJarKey ? repairCookieJar(stored) : stored;
|
|
194
|
+
},
|
|
195
|
+
}
|
|
196
|
+
: {}),
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
type BetterAuthFetchOptions = NonNullable<
|
|
200
|
+
NonNullable<Parameters<typeof createAuthClient>[0]>["fetchOptions"]
|
|
201
|
+
>;
|
|
202
|
+
type BetterAuthRequestHook = NonNullable<BetterAuthFetchOptions["onRequest"]>;
|
|
203
|
+
type BetterAuthSuccessHook = NonNullable<BetterAuthFetchOptions["onSuccess"]>;
|
|
204
|
+
type BetterAuthResponseHook = NonNullable<BetterAuthFetchOptions["onResponse"]>;
|
|
205
|
+
|
|
206
|
+
const isAuthEndpoint = (url: string | URL, endpoint: string): boolean => {
|
|
207
|
+
return new URL(url.toString(), "http://localhost").pathname.endsWith(endpoint);
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The header `@terreno/api` uses to carry Better Auth's signed challenge cookies (two-factor,
|
|
212
|
+
* trust-device, passkey) to and from clients that send no cookies.
|
|
213
|
+
*/
|
|
214
|
+
const AUTH_CHALLENGE_HEADER = "X-Terreno-Auth-Challenge";
|
|
215
|
+
|
|
216
|
+
// Sent when nothing is held, so the server still knows to answer with the header.
|
|
217
|
+
const AUTH_CHALLENGE_EMPTY = "-";
|
|
218
|
+
|
|
219
|
+
// Better Auth paths whose requests read challenge cookies (a trusted device is checked at sign-in).
|
|
220
|
+
const AUTH_CHALLENGE_PATHS = ["/two-factor/", "/passkey/", "/sign-in/"];
|
|
221
|
+
|
|
222
|
+
// Successful calls to these end the two-factor challenge.
|
|
223
|
+
const TWO_FACTOR_VERIFY_PATHS = [
|
|
224
|
+
"/two-factor/verify-totp",
|
|
225
|
+
"/two-factor/verify-otp",
|
|
226
|
+
"/two-factor/verify-backup-code",
|
|
227
|
+
];
|
|
228
|
+
|
|
229
|
+
const authChallengeKey = (storagePrefix?: string): string => {
|
|
230
|
+
return `${storagePrefix ?? DEFAULT_STORAGE_PREFIX}_auth_challenge`;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const isChallengeEndpoint = (url: string | URL): boolean => {
|
|
234
|
+
const {pathname} = new URL(url.toString(), "http://localhost");
|
|
235
|
+
return AUTH_CHALLENGE_PATHS.some((path) => pathname.includes(path));
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// Cookie names carry Better Auth's prefix (`better-auth.trust_device`, maybe `__Secure-`).
|
|
239
|
+
const isCookieNamed = (name: string, cookie: string): boolean => {
|
|
240
|
+
return name === cookie || name.endsWith(`.${cookie}`);
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const sentBearerToken = (headers: Headers): string | null => {
|
|
244
|
+
const authorization = headers.get("authorization");
|
|
245
|
+
if (!authorization?.startsWith("Bearer ")) {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
return authorization.slice("Bearer ".length);
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* better-fetch options that authenticate every Better Auth call with a stored bearer token and
|
|
253
|
+
* no cookies. They are client-wide defaults: per-call hooks still run alongside them, but a
|
|
254
|
+
* per-call `auth` or `credentials` overrides them.
|
|
255
|
+
*/
|
|
256
|
+
const createWebBearerFetchOptions = ({
|
|
257
|
+
bearerStorage,
|
|
258
|
+
storagePrefix,
|
|
259
|
+
}: {
|
|
260
|
+
bearerStorage?: BetterAuthBearerStorage;
|
|
261
|
+
storagePrefix?: string;
|
|
262
|
+
}): BetterAuthFetchOptions => {
|
|
263
|
+
// Resolved per access so a client created before `window` exists (SSR) still finds storage.
|
|
264
|
+
const storage = (): BetterAuthBearerStorage => resolveBearerStorage(bearerStorage);
|
|
265
|
+
const tokenKey = bearerTokenKey(storagePrefix);
|
|
266
|
+
const readToken = (): string | null => storage().getItem(tokenKey);
|
|
267
|
+
|
|
268
|
+
// The challenge cookies the server handed over, as `name=value` pairs, beside the bearer.
|
|
269
|
+
const challengeKey = authChallengeKey(storagePrefix);
|
|
270
|
+
const readChallenge = (): URLSearchParams => {
|
|
271
|
+
const stored = storage().getItem(challengeKey);
|
|
272
|
+
return new URLSearchParams(stored && stored !== AUTH_CHALLENGE_EMPTY ? stored : "");
|
|
273
|
+
};
|
|
274
|
+
const writeChallenge = (pairs: URLSearchParams): void => {
|
|
275
|
+
if (pairs.size === 0) {
|
|
276
|
+
storage().removeItem(challengeKey);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
storage().setItem(challengeKey, pairs.toString());
|
|
280
|
+
};
|
|
281
|
+
// Keeps only the entries `keep` accepts.
|
|
282
|
+
const filterChallenge = (keep: (name: string) => boolean): void => {
|
|
283
|
+
const pairs = readChallenge();
|
|
284
|
+
for (const name of Array.from(pairs.keys())) {
|
|
285
|
+
if (!keep(name)) {
|
|
286
|
+
pairs.delete(name);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
writeChallenge(pairs);
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
// Counts sign-outs, so a token issued by a request that was in flight across one is dropped.
|
|
293
|
+
let signOutCount = 0;
|
|
294
|
+
const signOutCountAtRequest = new WeakMap<object, number>();
|
|
295
|
+
|
|
296
|
+
// Runs after the request headers are built and before fetch, so the sign-out request still
|
|
297
|
+
// carries the token for the server to revoke while the device forgets it whatever happens next.
|
|
298
|
+
// Challenge calls carry the held challenge cookies; nothing else ever sees them.
|
|
299
|
+
const onRequest: BetterAuthRequestHook = (context) => {
|
|
300
|
+
if (isAuthEndpoint(context.url, "/sign-out")) {
|
|
301
|
+
signOutCount += 1;
|
|
302
|
+
storage().removeItem(tokenKey);
|
|
303
|
+
// A trusted device stays trusted across sign-outs; pending challenges do not.
|
|
304
|
+
filterChallenge((name) => isCookieNamed(name, "trust_device"));
|
|
305
|
+
}
|
|
306
|
+
signOutCountAtRequest.set(context, signOutCount);
|
|
307
|
+
if (isChallengeEndpoint(context.url)) {
|
|
308
|
+
const held = readChallenge();
|
|
309
|
+
context.headers.set(
|
|
310
|
+
AUTH_CHALLENGE_HEADER,
|
|
311
|
+
held.size > 0 ? held.toString() : AUTH_CHALLENGE_EMPTY
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
// Runs for every status before onSuccess (so before onTwoFactorRedirect), since a refused
|
|
317
|
+
// verify can also expire a challenge. An empty value means the server expired that cookie.
|
|
318
|
+
const onResponse: BetterAuthResponseHook = (context) => {
|
|
319
|
+
const header = context.response.headers.get(AUTH_CHALLENGE_HEADER);
|
|
320
|
+
if (header) {
|
|
321
|
+
const pairs = readChallenge();
|
|
322
|
+
for (const [name, value] of new URLSearchParams(header)) {
|
|
323
|
+
if (value) {
|
|
324
|
+
pairs.set(name, value);
|
|
325
|
+
} else {
|
|
326
|
+
pairs.delete(name);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
writeChallenge(pairs);
|
|
330
|
+
}
|
|
331
|
+
const isVerified =
|
|
332
|
+
context.response.ok &&
|
|
333
|
+
TWO_FACTOR_VERIFY_PATHS.some((path) => isAuthEndpoint(context.request.url, path));
|
|
334
|
+
// The challenge and the sign-in's "don't remember me" belong to the finished sign-in.
|
|
335
|
+
if (isVerified) {
|
|
336
|
+
filterChallenge(
|
|
337
|
+
(name) => !isCookieNamed(name, "two_factor") && !isCookieNamed(name, "dont_remember")
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// Only 2xx responses reach onSuccess, so a failed or 5xx get-session never clears the token.
|
|
343
|
+
const onSuccess: BetterAuthSuccessHook = (context) => {
|
|
344
|
+
const issuedToken = context.response.headers.get("set-auth-token");
|
|
345
|
+
// A sign-in waiting on a second factor has no session yet; any token it carries is dead.
|
|
346
|
+
if ((context.data as {twoFactorRedirect?: boolean} | null)?.twoFactorRedirect) {
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (issuedToken) {
|
|
350
|
+
// better-fetch hands onSuccess the same context object that onRequest saw.
|
|
351
|
+
const countAtRequest = signOutCountAtRequest.get(context.request) ?? signOutCount;
|
|
352
|
+
if (countAtRequest === signOutCount) {
|
|
353
|
+
storage().setItem(tokenKey, issuedToken);
|
|
354
|
+
}
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
if (!isAuthEndpoint(context.request.url, "/get-session")) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if ((context.data as {session?: unknown} | null)?.session) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
// The server rejected the token this request sent. A token stored while it was in flight
|
|
364
|
+
// (a sign-in that finished first) is newer and must survive.
|
|
365
|
+
if (sentBearerToken(context.request.headers) === readToken()) {
|
|
366
|
+
storage().removeItem(tokenKey);
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
return {
|
|
371
|
+
auth: {token: (): string | undefined => readToken() ?? undefined, type: "Bearer"},
|
|
372
|
+
credentials: "omit",
|
|
373
|
+
onRequest,
|
|
374
|
+
onResponse,
|
|
375
|
+
onSuccess,
|
|
376
|
+
};
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
// Better Auth appends `/api/auth` to a baseURL that has no path of its own.
|
|
380
|
+
const resolveAuthBaseURL = (baseURL: string): string => {
|
|
381
|
+
const trimmed = baseURL.replace(/\/+$/, "");
|
|
382
|
+
try {
|
|
383
|
+
if (new URL(baseURL).pathname.replace(/\/+$/, "") !== "") {
|
|
384
|
+
return trimmed;
|
|
385
|
+
}
|
|
386
|
+
} catch {
|
|
387
|
+
// Better Auth rejects such a baseURL itself when the client is created.
|
|
388
|
+
}
|
|
389
|
+
return `${trimmed}/api/auth`;
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
// The client plugin a feature adds when it is on. A feature set to `false`, or left out, adds
|
|
393
|
+
// nothing; a widened `boolean` (read from env, say) is typed as on.
|
|
394
|
+
type FeaturePlugin<
|
|
395
|
+
Features extends BetterAuthClientFeatures,
|
|
396
|
+
Key extends keyof BetterAuthClientFeatures,
|
|
397
|
+
Plugin,
|
|
398
|
+
> = Key extends keyof Features ? ([Features[Key]] extends [false | undefined] ? [] : [Plugin]) : [];
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* The typed client plugins for a `features` object, in the order `createBetterAuthClient`
|
|
402
|
+
* registers them. Better Auth infers each namespace (`client.twoFactor`, `client.passkey`, ...)
|
|
403
|
+
* from this tuple.
|
|
404
|
+
*/
|
|
405
|
+
export type BetterAuthFeaturePlugins<Features extends BetterAuthClientFeatures> = [
|
|
406
|
+
...FeaturePlugin<Features, "twoFactor", ReturnType<typeof twoFactorClient>>,
|
|
407
|
+
...FeaturePlugin<Features, "passkey", ReturnType<typeof passkeyClient>>,
|
|
408
|
+
...FeaturePlugin<Features, "multiSession", ReturnType<typeof multiSessionClient>>,
|
|
409
|
+
...FeaturePlugin<Features, "lastLoginMethod", ReturnType<typeof lastLoginMethodClient>>,
|
|
410
|
+
...FeaturePlugin<Features, "oneTimeToken", ReturnType<typeof oneTimeTokenClient>>,
|
|
411
|
+
];
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Type of the Better Auth client returned by createBetterAuthClient without `features`.
|
|
415
|
+
*/
|
|
416
|
+
export type BetterAuthClient = ReactAuthClient<{
|
|
417
|
+
baseURL: string;
|
|
418
|
+
fetchOptions?: BetterAuthFetchOptions;
|
|
419
|
+
plugins: [ExpoAuthClientPlugin];
|
|
420
|
+
}>;
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Type of the Better Auth client returned by createBetterAuthClient with `features`, such as
|
|
424
|
+
* `BetterAuthClientWithFeatures<{twoFactor: true}>`. Every enabled feature's namespace is typed.
|
|
425
|
+
*
|
|
426
|
+
* The expo plugin is typed by the narrow {@link ExpoAuthClientPlugin} (it adds only `getCookie`),
|
|
427
|
+
* because the generic `BetterAuthClientPlugin` would widen every namespace to `any`.
|
|
428
|
+
*/
|
|
429
|
+
export type BetterAuthClientWithFeatures<Features extends BetterAuthClientFeatures> =
|
|
430
|
+
ReactAuthClient<{
|
|
431
|
+
baseURL: string;
|
|
432
|
+
fetchOptions?: BetterAuthFetchOptions;
|
|
433
|
+
plugins: [ExpoAuthClientPlugin, ...BetterAuthFeaturePlugins<Features>];
|
|
434
|
+
}>;
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* What the OAuth handoff helpers need from a client: any client createBetterAuthClient returns,
|
|
438
|
+
* with or without features.
|
|
439
|
+
*/
|
|
440
|
+
export type BetterAuthHandoffClient = Pick<BetterAuthClient, "$fetch" | "$store">;
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* The client createBetterAuthClient returns for a `features` type. When the features are not
|
|
444
|
+
* known at compile time (no `features`, or a config typed as `BetterAuthClientConfig`), it is
|
|
445
|
+
* `BetterAuthClient`, exactly the client it always returned. When they are written out, every
|
|
446
|
+
* enabled feature's namespace is typed.
|
|
447
|
+
*/
|
|
448
|
+
export type BetterAuthClientFor<Features extends BetterAuthClientFeatures> =
|
|
449
|
+
BetterAuthClientFeatures extends Features
|
|
450
|
+
? BetterAuthClient
|
|
451
|
+
: BetterAuthClientWithFeatures<Features>;
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Builds the client plugins for the enabled features, in BetterAuthFeaturePlugins order. They go
|
|
455
|
+
* after the expo plugin: better-fetch runs plugin hooks in order, so on native the expo plugin
|
|
456
|
+
* stores the 2FA challenge cookie before `onTwoFactorRedirect` runs, and its request hook adds the
|
|
457
|
+
* stored cookies to every feature call.
|
|
458
|
+
*/
|
|
459
|
+
const createFeaturePlugins = (features?: BetterAuthClientFeatures): BetterAuthClientPlugin[] => {
|
|
460
|
+
if (!features) {
|
|
461
|
+
return [];
|
|
462
|
+
}
|
|
463
|
+
const plugins: BetterAuthClientPlugin[] = [];
|
|
464
|
+
if (features.twoFactor) {
|
|
465
|
+
plugins.push(twoFactorClient(features.twoFactor === true ? undefined : features.twoFactor));
|
|
466
|
+
}
|
|
467
|
+
if (features.passkey) {
|
|
468
|
+
// Same declared-vs-structural mismatch as expoClient below.
|
|
469
|
+
plugins.push(passkeyClient() as unknown as BetterAuthClientPlugin);
|
|
470
|
+
}
|
|
471
|
+
if (features.multiSession) {
|
|
472
|
+
plugins.push(multiSessionClient());
|
|
473
|
+
}
|
|
474
|
+
if (features.lastLoginMethod) {
|
|
475
|
+
plugins.push(lastLoginMethodClient());
|
|
476
|
+
}
|
|
477
|
+
if (features.oneTimeToken) {
|
|
478
|
+
plugins.push(oneTimeTokenClient());
|
|
479
|
+
}
|
|
480
|
+
return plugins;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Creates a Better Auth client configured for Expo/React Native.
|
|
485
|
+
*
|
|
486
|
+
* Pass `webAuth: "bearer"` when the web frontend and the API are on different sites: the web
|
|
487
|
+
* client then authenticates with a stored bearer token instead of cookies. Read that token
|
|
488
|
+
* elsewhere with `getBetterAuthBearerToken`.
|
|
489
|
+
*
|
|
490
|
+
* Pass `features` to add the client plugins for the Better Auth features the server enables.
|
|
491
|
+
* Each one adds a typed namespace: `client.twoFactor`, `client.passkey`, `client.multiSession`,
|
|
492
|
+
* `client.oneTimeToken`, and `client.getLastUsedLoginMethod`.
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* ```typescript
|
|
496
|
+
* const authClient = createBetterAuthClient({
|
|
497
|
+
* baseURL: "http://localhost:3000",
|
|
498
|
+
* features: {passkey: true, twoFactor: {onTwoFactorRedirect: () => router.push("/2fa")}},
|
|
499
|
+
* scheme: "terreno",
|
|
500
|
+
* });
|
|
501
|
+
*
|
|
502
|
+
* // Use for social login
|
|
503
|
+
* await authClient.signIn.social({
|
|
504
|
+
* provider: "google",
|
|
505
|
+
* });
|
|
506
|
+
*
|
|
507
|
+
* // Get current session
|
|
508
|
+
* const session = await authClient.getSession();
|
|
509
|
+
*
|
|
510
|
+
* // Feature namespaces are typed
|
|
511
|
+
* await authClient.twoFactor.enable({password});
|
|
512
|
+
* ```
|
|
513
|
+
*/
|
|
514
|
+
export const createBetterAuthClient = <
|
|
515
|
+
const Features extends BetterAuthClientFeatures = BetterAuthClientFeatures,
|
|
516
|
+
>(
|
|
517
|
+
config: BetterAuthClientConfig<Features>
|
|
518
|
+
): BetterAuthClientFor<Features> => {
|
|
519
|
+
const storagePrefix = config.storagePrefix ?? DEFAULT_STORAGE_PREFIX;
|
|
520
|
+
// Mirrors the plugin's own `cookieName = `${storagePrefix}_cookie``.
|
|
521
|
+
const storage = withCookieJarRepair({
|
|
522
|
+
cookieJarKey: `${storagePrefix}_cookie`,
|
|
523
|
+
storage: createStorageAdapter(),
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
// `expoClient` declares `getActions` against a narrowed `BetterFetch<CreateFetchOption, ...>`
|
|
527
|
+
// while `BetterAuthClientPlugin` declares the unparameterized `BetterFetch`, so the plugin
|
|
528
|
+
// does not structurally satisfy its own contract. Runtime behaviour is unaffected; the
|
|
529
|
+
// narrow `ExpoAuthClientPlugin` keeps the full client type (see its note).
|
|
530
|
+
const expoAuthPlugin = expoClient({
|
|
531
|
+
scheme: config.scheme,
|
|
532
|
+
// The plugin's storage type is strictly sync (`getItem: (key) => string | null`),
|
|
533
|
+
// which the native branch satisfies. The union-typed web branch is async but
|
|
534
|
+
// unreachable here, since the plugin skips storage entirely on web.
|
|
535
|
+
storage: storage as unknown as ExpoClientStorage,
|
|
536
|
+
storagePrefix,
|
|
537
|
+
}) as unknown as ExpoAuthClientPlugin;
|
|
538
|
+
|
|
539
|
+
// Native and cookie mode pass exactly the options they always have.
|
|
540
|
+
const isWebBearer = IsWeb && config.webAuth === "bearer";
|
|
541
|
+
|
|
542
|
+
const client = createAuthClient({
|
|
543
|
+
baseURL: config.baseURL,
|
|
544
|
+
plugins: [expoAuthPlugin, ...createFeaturePlugins(config.features)],
|
|
545
|
+
...(isWebBearer
|
|
546
|
+
? {
|
|
547
|
+
fetchOptions: createWebBearerFetchOptions({
|
|
548
|
+
bearerStorage: config.bearerStorage,
|
|
549
|
+
storagePrefix,
|
|
550
|
+
}),
|
|
551
|
+
}
|
|
552
|
+
: {}),
|
|
553
|
+
});
|
|
554
|
+
handoffClients.set(client, {
|
|
555
|
+
authBaseURL: resolveAuthBaseURL(config.baseURL),
|
|
556
|
+
bearerStorage: config.bearerStorage,
|
|
557
|
+
isWebBearer,
|
|
558
|
+
storagePrefix,
|
|
559
|
+
});
|
|
560
|
+
// The plugins are built at runtime from `features`; BetterAuthClientFor is their type.
|
|
561
|
+
return client as unknown as BetterAuthClientFor<Features>;
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
// URL parameters of the OAuth handoff: T12's server puts the one-time token in the fragment as
|
|
565
|
+
// `ott`, and the sign-in's nonce comes back in the callback query as `handoff`.
|
|
566
|
+
const HANDOFF_TOKEN_PARAM = "ott";
|
|
567
|
+
const HANDOFF_NONCE_PARAM = "handoff";
|
|
568
|
+
const HANDOFF_NONCE_BYTES = 32;
|
|
569
|
+
|
|
570
|
+
const handoffNonceKey = (storagePrefix: string): string => {
|
|
571
|
+
return `${storagePrefix}_oauth_handoff_nonce`;
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
const NOT_WEB_BEARER_MESSAGE =
|
|
575
|
+
'signInSocialWithHandoff needs a web client from createBetterAuthClient({webAuth: "bearer"}). ' +
|
|
576
|
+
"Use authClient.signIn.social on native and in cookie mode.";
|
|
577
|
+
|
|
578
|
+
const createHandoffNonce = (): string => {
|
|
579
|
+
// A crypto-random nonce only: a guessable one would let a planted token through.
|
|
580
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(HANDOFF_NONCE_BYTES));
|
|
581
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
// Compares every character so the time taken does not depend on where the strings differ.
|
|
585
|
+
const nonceMatches = (received: string, stored: string): boolean => {
|
|
586
|
+
if (received.length !== stored.length) {
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
let difference = 0;
|
|
590
|
+
for (let index = 0; index < received.length; index += 1) {
|
|
591
|
+
difference |= received.charCodeAt(index) ^ stored.charCodeAt(index);
|
|
592
|
+
}
|
|
593
|
+
return difference === 0;
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
const decodeParamPart = (part: string): string | null => {
|
|
597
|
+
try {
|
|
598
|
+
return decodeURIComponent(part.replace(/\+/g, " "));
|
|
599
|
+
} catch {
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Splits a raw query or fragment (without its `?` or `#`) into the values of `name` and the
|
|
606
|
+
* other parts, kept byte-for-byte so stripping never re-encodes what the app put there.
|
|
607
|
+
*/
|
|
608
|
+
const takeParam = (raw: string, name: string): {kept: string[]; values: Array<string | null>} => {
|
|
609
|
+
const kept: string[] = [];
|
|
610
|
+
const values: Array<string | null> = [];
|
|
611
|
+
for (const part of raw.split("&")) {
|
|
612
|
+
if (part === "") {
|
|
613
|
+
continue;
|
|
614
|
+
}
|
|
615
|
+
const separator = part.indexOf("=");
|
|
616
|
+
const key = separator === -1 ? part : part.slice(0, separator);
|
|
617
|
+
if (decodeParamPart(key) !== name) {
|
|
618
|
+
kept.push(part);
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
values.push(separator === -1 ? "" : decodeParamPart(part.slice(separator + 1)));
|
|
622
|
+
}
|
|
623
|
+
return {kept, values};
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
const sessionStorageOrNull = (): BetterAuthBearerStorage | null => {
|
|
627
|
+
try {
|
|
628
|
+
return window.sessionStorage ?? null;
|
|
629
|
+
} catch {
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
// Reads and removes the nonce in one step, so each sign-in's nonce is good for one return only.
|
|
635
|
+
const takeStoredNonce = (storagePrefix: string): string | null => {
|
|
636
|
+
const storage = sessionStorageOrNull();
|
|
637
|
+
if (!storage) {
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
try {
|
|
641
|
+
const nonce = storage.getItem(handoffNonceKey(storagePrefix));
|
|
642
|
+
storage.removeItem(handoffNonceKey(storagePrefix));
|
|
643
|
+
return nonce;
|
|
644
|
+
} catch {
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
|
|
649
|
+
// Appends `handoff=<nonce>` to the query as written, so the app's own parameters reach the
|
|
650
|
+
// return page byte-for-byte. Any `handoff` already there is replaced.
|
|
651
|
+
const withHandoffNonce = (url: string, nonce: string): string => {
|
|
652
|
+
const parsed = new URL(url, window.location.href);
|
|
653
|
+
const {kept} = takeParam(parsed.search.slice(1), HANDOFF_NONCE_PARAM);
|
|
654
|
+
kept.push(`${HANDOFF_NONCE_PARAM}=${nonce}`);
|
|
655
|
+
return `${parsed.origin}${parsed.pathname}?${kept.join("&")}${parsed.hash}`;
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* Starts a social or generic OAuth sign-in for a web client in bearer mode. It stores a random
|
|
660
|
+
* nonce in sessionStorage and navigates the whole page to the server's
|
|
661
|
+
* `GET {basePath}/oauth-handoff/start`, with `handoff=<nonce>` added to `callbackURL` (and to
|
|
662
|
+
* `errorCallbackURL`). A top-level navigation keeps Better Auth's OAuth state cookie
|
|
663
|
+
* first-party on the API's origin. After the provider, the page comes back to `callbackURL`
|
|
664
|
+
* with `#ott=<token>`, and `completeBetterAuthOAuthHandoff` exchanges it for the bearer.
|
|
665
|
+
*
|
|
666
|
+
* `callbackURL` defaults to `/` on the current origin (pass the full path for an app served
|
|
667
|
+
* under a sub-path). It is resolved against the current page, and its path must be one of the
|
|
668
|
+
* server's `oauthHandoff.callbackPaths` (default `["/"]`) on one of its
|
|
669
|
+
* `oauthHandoff.webOrigins`, or the server answers 400. `errorCallbackURL` defaults to
|
|
670
|
+
* `callbackURL`; a failed start or callback comes back there with `?error=`. It is always sent,
|
|
671
|
+
* because without one Better Auth sends callback errors to its own error page on the API.
|
|
672
|
+
*
|
|
673
|
+
* Throws on native, in cookie mode, for a client `createBetterAuthClient` did not make, and
|
|
674
|
+
* when sessionStorage cannot hold the nonce. Use `authClient.signIn.social` in those cases.
|
|
675
|
+
*
|
|
676
|
+
* @example
|
|
677
|
+
* ```typescript
|
|
678
|
+
* <SocialLoginButton
|
|
679
|
+
* provider="google"
|
|
680
|
+
* onPress={() => signInSocialWithHandoff({client: authClient, provider: "google"})}
|
|
681
|
+
* />
|
|
682
|
+
* ```
|
|
683
|
+
*/
|
|
684
|
+
export const signInSocialWithHandoff = ({
|
|
685
|
+
callbackURL = "/",
|
|
686
|
+
client,
|
|
687
|
+
errorCallbackURL,
|
|
688
|
+
provider,
|
|
689
|
+
}: {
|
|
690
|
+
callbackURL?: string;
|
|
691
|
+
client: BetterAuthHandoffClient;
|
|
692
|
+
errorCallbackURL?: string;
|
|
693
|
+
provider: string;
|
|
694
|
+
}): void => {
|
|
695
|
+
const config = handoffClients.get(client);
|
|
696
|
+
if (!IsWeb || typeof window === "undefined" || !config?.isWebBearer) {
|
|
697
|
+
throw new Error(NOT_WEB_BEARER_MESSAGE);
|
|
698
|
+
}
|
|
699
|
+
const nonce = createHandoffNonce();
|
|
700
|
+
const start = new URL(`${config.authBaseURL}/oauth-handoff/start`);
|
|
701
|
+
start.searchParams.set("provider", provider);
|
|
702
|
+
start.searchParams.set("callbackURL", withHandoffNonce(callbackURL, nonce));
|
|
703
|
+
start.searchParams.set(
|
|
704
|
+
"errorCallbackURL",
|
|
705
|
+
withHandoffNonce(errorCallbackURL ?? callbackURL, nonce)
|
|
706
|
+
);
|
|
707
|
+
// Throws when storage is blocked: without a stored nonce the return would be refused anyway.
|
|
708
|
+
window.sessionStorage.setItem(handoffNonceKey(config.storagePrefix), nonce);
|
|
709
|
+
window.location.assign(start.toString());
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* Removes the handoff from the page URL and returns the one-time token when this tab started
|
|
714
|
+
* the sign-in, or null. Runs synchronously, so a second call made before the first finishes
|
|
715
|
+
* finds a clean URL.
|
|
716
|
+
*/
|
|
717
|
+
const takeHandoffToken = (
|
|
718
|
+
client: BetterAuthHandoffClient
|
|
719
|
+
): {config: HandoffClientConfig; token: string} | null => {
|
|
720
|
+
let current: URL;
|
|
721
|
+
try {
|
|
722
|
+
current = new URL(window.location.href);
|
|
723
|
+
} catch {
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
const query = takeParam(current.search.slice(1), HANDOFF_NONCE_PARAM);
|
|
727
|
+
// The server only puts the token in the fragment. An `ott` in the query was planted: it is
|
|
728
|
+
// removed from the URL with the rest and never sent.
|
|
729
|
+
const queryToken = takeParam(query.kept.join("&"), HANDOFF_TOKEN_PARAM);
|
|
730
|
+
const fragment = takeParam(current.hash.slice(1), HANDOFF_TOKEN_PARAM);
|
|
731
|
+
const hasHandoff =
|
|
732
|
+
query.values.length > 0 || queryToken.values.length > 0 || fragment.values.length > 0;
|
|
733
|
+
if (!hasHandoff) {
|
|
734
|
+
return null;
|
|
735
|
+
}
|
|
736
|
+
const config = handoffClients.get(client);
|
|
737
|
+
const storedNonce = config ? takeStoredNonce(config.storagePrefix) : null;
|
|
738
|
+
|
|
739
|
+
// The token leaves the address bar, and so history, before anything else can read or send it.
|
|
740
|
+
const search = queryToken.kept.length > 0 ? `?${queryToken.kept.join("&")}` : "";
|
|
741
|
+
const hash = fragment.kept.length > 0 ? `#${fragment.kept.join("&")}` : "";
|
|
742
|
+
try {
|
|
743
|
+
window.history.replaceState(window.history.state, "", `${current.pathname}${search}${hash}`);
|
|
744
|
+
} catch (error) {
|
|
745
|
+
console.warn(
|
|
746
|
+
"[terreno/syncdb] Could not remove the OAuth handoff from the URL; not verifying",
|
|
747
|
+
{
|
|
748
|
+
errorName: error instanceof Error ? error.name : typeof error,
|
|
749
|
+
}
|
|
750
|
+
);
|
|
751
|
+
return null;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (!config?.isWebBearer || fragment.values.length !== 1 || query.values.length !== 1) {
|
|
755
|
+
return null;
|
|
756
|
+
}
|
|
757
|
+
const [token] = fragment.values;
|
|
758
|
+
const [receivedNonce] = query.values;
|
|
759
|
+
// A token without the nonce this tab stored was planted, so it is never sent.
|
|
760
|
+
if (!token || !receivedNonce || !storedNonce || !nonceMatches(receivedNonce, storedNonce)) {
|
|
761
|
+
return null;
|
|
762
|
+
}
|
|
763
|
+
return {config, token};
|
|
764
|
+
};
|
|
765
|
+
|
|
766
|
+
const verifyHandoffToken = async ({
|
|
767
|
+
client,
|
|
768
|
+
config,
|
|
769
|
+
token,
|
|
770
|
+
}: {
|
|
771
|
+
client: BetterAuthHandoffClient;
|
|
772
|
+
config: HandoffClientConfig;
|
|
773
|
+
token: string;
|
|
774
|
+
}): Promise<boolean> => {
|
|
775
|
+
let issuedToken: string | null = null;
|
|
776
|
+
try {
|
|
777
|
+
// Through the client, so bearer mode's hooks store the token and apply the sign-out guard.
|
|
778
|
+
const result = await client.$fetch("/one-time-token/verify", {
|
|
779
|
+
body: {token},
|
|
780
|
+
method: "POST",
|
|
781
|
+
onSuccess: (context): void => {
|
|
782
|
+
issuedToken = context.response.headers.get("set-auth-token");
|
|
783
|
+
},
|
|
784
|
+
});
|
|
785
|
+
if (result.error) {
|
|
786
|
+
console.warn("[terreno/syncdb] OAuth handoff verify was refused", {
|
|
787
|
+
status: result.error.status,
|
|
788
|
+
});
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
if (!issuedToken) {
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
const stored = getBetterAuthBearerToken({
|
|
795
|
+
bearerStorage: config.bearerStorage,
|
|
796
|
+
storagePrefix: config.storagePrefix,
|
|
797
|
+
});
|
|
798
|
+
if (stored !== issuedToken) {
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
} catch (error) {
|
|
802
|
+
console.warn("[terreno/syncdb] OAuth handoff verify failed", {
|
|
803
|
+
errorName: error instanceof Error ? error.name : typeof error,
|
|
804
|
+
});
|
|
805
|
+
return false;
|
|
806
|
+
}
|
|
807
|
+
// `$fetch` skips the session signal that the client's own routes send, so a mounted
|
|
808
|
+
// `useSession` refetches with the new token.
|
|
809
|
+
client.$store?.notify("$sessionSignal");
|
|
810
|
+
return true;
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
const pendingHandoffs = new WeakMap<object, Promise<boolean>>();
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Finishes a sign-in that `signInSocialWithHandoff` started, on the page the provider sent the
|
|
817
|
+
* browser back to. Await it once at startup, before anything reads the session, before any code
|
|
818
|
+
* acts on other query parameters, and before Sentry or analytics start.
|
|
819
|
+
*
|
|
820
|
+
* When the URL has `#ott=<token>` and `?handoff=` equal to the nonce this tab stored, it removes
|
|
821
|
+
* `ott`, `handoff` and the stored nonce (`history.replaceState`), then exchanges the token at
|
|
822
|
+
* `POST {basePath}/one-time-token/verify`. Bearer mode stores the `set-auth-token` that comes
|
|
823
|
+
* back. Other query and fragment parts are kept. A token without a matching nonce, or an `ott`
|
|
824
|
+
* in the query (the server only uses the fragment), is removed from the URL and never sent. Native, cookie mode, and a page without `ott` make no request.
|
|
825
|
+
*
|
|
826
|
+
* Resolves `true` only when a bearer token was stored, and never rejects. A return with
|
|
827
|
+
* `?error=` (such as `provider_not_found` or `sign_in_failed`) resolves `false` and leaves the
|
|
828
|
+
* error in the URL for the app to show. Calls made while one is running share its result.
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* ```typescript
|
|
832
|
+
* await completeBetterAuthOAuthHandoff({client: authClient});
|
|
833
|
+
* await session.refresh(); // useSession() from @terreno/syncdb/auth
|
|
834
|
+
* ```
|
|
835
|
+
*/
|
|
836
|
+
export const completeBetterAuthOAuthHandoff = ({
|
|
837
|
+
client,
|
|
838
|
+
}: {
|
|
839
|
+
client: BetterAuthHandoffClient;
|
|
840
|
+
}): Promise<boolean> => {
|
|
841
|
+
if (!IsWeb || typeof window === "undefined") {
|
|
842
|
+
return Promise.resolve(false);
|
|
843
|
+
}
|
|
844
|
+
const pending = pendingHandoffs.get(client);
|
|
845
|
+
if (pending !== undefined) {
|
|
846
|
+
return pending;
|
|
847
|
+
}
|
|
848
|
+
const handoff = takeHandoffToken(client);
|
|
849
|
+
if (!handoff) {
|
|
850
|
+
return Promise.resolve(false);
|
|
851
|
+
}
|
|
852
|
+
const result = verifyHandoffToken({client, ...handoff}).finally(() => {
|
|
853
|
+
pendingHandoffs.delete(client);
|
|
854
|
+
});
|
|
855
|
+
pendingHandoffs.set(client, result);
|
|
856
|
+
return result;
|
|
857
|
+
};
|
|
858
|
+
|
|
859
|
+
/** The part of a typed client (one made with `features`) that linking calls. */
|
|
860
|
+
interface LinkSocialClient extends Pick<BetterAuthClient, "$fetch"> {
|
|
861
|
+
// Method syntax, so each client's own `linkSocial` (whose `provider` may be a narrower union)
|
|
862
|
+
// still fits.
|
|
863
|
+
linkSocial(body: {
|
|
864
|
+
callbackURL: string;
|
|
865
|
+
errorCallbackURL?: string;
|
|
866
|
+
provider: string;
|
|
867
|
+
}): Promise<{error: {code?: string; message?: string; status: number} | null}>;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* What linking needs from a client: any client createBetterAuthClient returns, with or without
|
|
872
|
+
* features. A client without `features` is typed loosely, so it is listed on its own.
|
|
873
|
+
*/
|
|
874
|
+
export type BetterAuthLinkClient = BetterAuthClient | LinkSocialClient;
|
|
875
|
+
|
|
876
|
+
/** Why a link could not start; `null` when the browser is on its way to the provider. */
|
|
877
|
+
export interface LinkSocialWithHandoffResult {
|
|
878
|
+
error: {code?: string; message?: string; status: number} | null;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
interface LinkIntentResponse {
|
|
882
|
+
startURL: string;
|
|
883
|
+
token: string;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const toLinkError = (error: {
|
|
887
|
+
code?: string;
|
|
888
|
+
message?: string;
|
|
889
|
+
status: number;
|
|
890
|
+
}): NonNullable<LinkSocialWithHandoffResult["error"]> => ({
|
|
891
|
+
status: error.status,
|
|
892
|
+
...(error.code !== undefined ? {code: error.code} : {}),
|
|
893
|
+
...(error.message !== undefined ? {message: error.message} : {}),
|
|
894
|
+
});
|
|
895
|
+
|
|
896
|
+
const isHttpURL = (url: unknown): url is string => {
|
|
897
|
+
if (typeof url !== "string") {
|
|
898
|
+
return false;
|
|
899
|
+
}
|
|
900
|
+
try {
|
|
901
|
+
const {protocol} = new URL(url);
|
|
902
|
+
return protocol === "http:" || protocol === "https:";
|
|
903
|
+
} catch {
|
|
904
|
+
return false;
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
// Posts the token from a hidden form, a top-level navigation, so the token stays out of the
|
|
909
|
+
// page URL, history, and access logs, and the API sets the state cookie first-party.
|
|
910
|
+
const submitLinkForm = (startURL: string, token: string): void => {
|
|
911
|
+
const form = window.document.createElement("form");
|
|
912
|
+
form.method = "POST";
|
|
913
|
+
form.action = startURL;
|
|
914
|
+
form.style.display = "none";
|
|
915
|
+
const field = window.document.createElement("input");
|
|
916
|
+
field.type = "hidden";
|
|
917
|
+
field.name = "token";
|
|
918
|
+
field.value = token;
|
|
919
|
+
form.appendChild(field);
|
|
920
|
+
window.document.body.appendChild(form);
|
|
921
|
+
form.submit();
|
|
922
|
+
};
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* Links a social or generic OAuth provider to the signed-in user.
|
|
926
|
+
*
|
|
927
|
+
* On web in bearer mode (`createBetterAuthClient({webAuth: "bearer"})`), a `POST /link-social`
|
|
928
|
+
* fetch from another site cannot set Better Auth's OAuth state cookie on the API's origin. So
|
|
929
|
+
* this posts `{provider, callbackURL, errorCallbackURL}` to the server's
|
|
930
|
+
* `POST {basePath}/oauth-handoff/link-intent` with the bearer, then submits the single-use token
|
|
931
|
+
* it returns in a hidden form (method POST) to `startURL`, which redirects the page to the
|
|
932
|
+
* provider. The provider sends the page back to `callbackURL`, with no token: linking creates no
|
|
933
|
+
* session. A failure after the form comes back to `errorCallbackURL` with `?error=`.
|
|
934
|
+
*
|
|
935
|
+
* Both URLs are resolved against the current page and may be any page on one of the server's
|
|
936
|
+
* `oauthHandoff.webOrigins` that its `trustedOrigins` allows. `oauthHandoff.callbackPaths` do not
|
|
937
|
+
* apply, since no token travels on a link's return. `errorCallbackURL` defaults to
|
|
938
|
+
* `callbackURL`. The page must not be served with `Referrer-Policy: no-referrer` or
|
|
939
|
+
* `same-origin`: the form's `Origin` header is then `null`, and the server refuses the start.
|
|
940
|
+
*
|
|
941
|
+
* In cookie mode and on native it calls `client.linkSocial` as before.
|
|
942
|
+
*
|
|
943
|
+
* Resolves `{error: null}` once the browser is on its way (or `linkSocial` succeeded), and
|
|
944
|
+
* `{error}` when the server refused, such as 403 `LINKING_DISABLED` when linking is off. It never
|
|
945
|
+
* submits the form after a refusal.
|
|
946
|
+
*
|
|
947
|
+
* @example
|
|
948
|
+
* ```typescript
|
|
949
|
+
* const {error} = await linkSocialWithHandoff({
|
|
950
|
+
* callbackURL: "/settings/security",
|
|
951
|
+
* client: authClient,
|
|
952
|
+
* errorCallbackURL: "/settings/security",
|
|
953
|
+
* provider: "google",
|
|
954
|
+
* });
|
|
955
|
+
* ```
|
|
956
|
+
*/
|
|
957
|
+
export const linkSocialWithHandoff = async ({
|
|
958
|
+
callbackURL,
|
|
959
|
+
client,
|
|
960
|
+
errorCallbackURL,
|
|
961
|
+
provider,
|
|
962
|
+
}: {
|
|
963
|
+
callbackURL: string;
|
|
964
|
+
client: BetterAuthLinkClient;
|
|
965
|
+
errorCallbackURL?: string;
|
|
966
|
+
provider: string;
|
|
967
|
+
}): Promise<LinkSocialWithHandoffResult> => {
|
|
968
|
+
const config = handoffClients.get(client);
|
|
969
|
+
if (!IsWeb || typeof window === "undefined" || !config?.isWebBearer) {
|
|
970
|
+
const result = await (client as LinkSocialClient).linkSocial({
|
|
971
|
+
callbackURL,
|
|
972
|
+
provider,
|
|
973
|
+
...(errorCallbackURL !== undefined ? {errorCallbackURL} : {}),
|
|
974
|
+
});
|
|
975
|
+
return {error: result.error ? toLinkError(result.error) : null};
|
|
976
|
+
}
|
|
977
|
+
const toAbsolute = (url: string): string => new URL(url, window.location.href).toString();
|
|
978
|
+
// Without an error page, Better Auth would send a failed link to its own page on the API.
|
|
979
|
+
const intent = await client.$fetch<LinkIntentResponse>("/oauth-handoff/link-intent", {
|
|
980
|
+
body: {
|
|
981
|
+
callbackURL: toAbsolute(callbackURL),
|
|
982
|
+
errorCallbackURL: toAbsolute(errorCallbackURL ?? callbackURL),
|
|
983
|
+
provider,
|
|
984
|
+
},
|
|
985
|
+
method: "POST",
|
|
986
|
+
});
|
|
987
|
+
if (intent.error) {
|
|
988
|
+
return {error: toLinkError(intent.error)};
|
|
989
|
+
}
|
|
990
|
+
const {startURL, token} = intent.data ?? {};
|
|
991
|
+
if (!token || !isHttpURL(startURL)) {
|
|
992
|
+
console.warn("[terreno/syncdb] The link intent answered without a usable token or start URL");
|
|
993
|
+
return {error: {message: "The link intent answered without a token", status: 500}};
|
|
994
|
+
}
|
|
995
|
+
submitLinkForm(startURL, token);
|
|
996
|
+
return {error: null};
|
|
997
|
+
};
|