@terreno/syncdb 57.21.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 +43 -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 +93 -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,2198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Isolated because these suites `mock.module` Better Auth and expo-secure-store. A shared
|
|
3
|
+
* `bun test` process would keep those replacements for every other syncdb file.
|
|
4
|
+
*/
|
|
5
|
+
import {afterAll, afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
|
|
6
|
+
import type {BetterAuthClient} from "../auth/betterAuthClient";
|
|
7
|
+
import type {BetterAuthClientFeatures, BetterAuthSessionClientLike} from "../auth/betterAuthTypes";
|
|
8
|
+
|
|
9
|
+
type ExpoOptions = {
|
|
10
|
+
scheme?: string;
|
|
11
|
+
storagePrefix?: string;
|
|
12
|
+
storage?: {
|
|
13
|
+
getItem: (key: string) => string | null | Promise<string | null>;
|
|
14
|
+
setItem: (key: string, value: string) => void | Promise<void>;
|
|
15
|
+
removeItem: (key: string) => void | Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const captured: {
|
|
20
|
+
auth: Record<string, unknown> | null;
|
|
21
|
+
// When set, createAuthClient returns this instead of a stub, so a test can hand
|
|
22
|
+
// createBetterAuthClient's caller a real client built from the options it passed.
|
|
23
|
+
build: ((config: Record<string, unknown>) => unknown) | null;
|
|
24
|
+
expo: ExpoOptions | null;
|
|
25
|
+
} = {
|
|
26
|
+
auth: null,
|
|
27
|
+
build: null,
|
|
28
|
+
expo: null,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
mock.module("@better-auth/expo/client", () => ({
|
|
32
|
+
expoClient: (options: ExpoOptions) => {
|
|
33
|
+
captured.expo = options;
|
|
34
|
+
return {name: "expo-plugin"};
|
|
35
|
+
},
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
mock.module("better-auth/react", () => ({
|
|
39
|
+
createAuthClient: (config: Record<string, unknown>) => {
|
|
40
|
+
captured.auth = config;
|
|
41
|
+
return captured.build ? captured.build(config) : {clientId: "mock-client", config};
|
|
42
|
+
},
|
|
43
|
+
}));
|
|
44
|
+
|
|
45
|
+
// A jar in the state that bricked native sign-in: the plugin's reader does `cookie.expires` on
|
|
46
|
+
// every entry, so the null entry threw a TypeError before any request was sent.
|
|
47
|
+
const CORRUPT_JAR = JSON.stringify({
|
|
48
|
+
"better-auth.session_data": {expires: null, value: "cached"},
|
|
49
|
+
"better-auth.session_token": null,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const secureCalls = {
|
|
53
|
+
delete: [] as string[],
|
|
54
|
+
get: [] as string[],
|
|
55
|
+
getSync: [] as string[],
|
|
56
|
+
set: [] as Array<[string, string]>,
|
|
57
|
+
setSync: [] as Array<[string, string]>,
|
|
58
|
+
};
|
|
59
|
+
const resetSecureCalls = (): void => {
|
|
60
|
+
secureCalls.delete = [];
|
|
61
|
+
secureCalls.get = [];
|
|
62
|
+
secureCalls.getSync = [];
|
|
63
|
+
secureCalls.set = [];
|
|
64
|
+
secureCalls.setSync = [];
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// mock.module registrations are global and last-writer-wins across test files (the
|
|
68
|
+
// test-preload registers a no-op expo-secure-store). Re-installing this tracking mock per
|
|
69
|
+
// test keeps the suite order-independent.
|
|
70
|
+
const mockSecureStore = (): void => {
|
|
71
|
+
mock.module("expo-secure-store", () => ({
|
|
72
|
+
deleteItemAsync: async (key: string): Promise<void> => {
|
|
73
|
+
secureCalls.delete.push(key);
|
|
74
|
+
},
|
|
75
|
+
getItem: (key: string): string | null => {
|
|
76
|
+
secureCalls.getSync.push(key);
|
|
77
|
+
return key.endsWith("_cookie") ? CORRUPT_JAR : `secure-${key}`;
|
|
78
|
+
},
|
|
79
|
+
getItemAsync: async (key: string): Promise<string | null> => {
|
|
80
|
+
secureCalls.get.push(key);
|
|
81
|
+
return `secure-${key}`;
|
|
82
|
+
},
|
|
83
|
+
setItem: (key: string, value: string): void => {
|
|
84
|
+
secureCalls.setSync.push([key, value]);
|
|
85
|
+
},
|
|
86
|
+
setItemAsync: async (key: string, value: string): Promise<void> => {
|
|
87
|
+
secureCalls.set.push([key, value]);
|
|
88
|
+
},
|
|
89
|
+
}));
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
mockSecureStore();
|
|
93
|
+
|
|
94
|
+
const AsyncStorage = (await import("@react-native-async-storage/async-storage")).default;
|
|
95
|
+
const {bridgeBetterAuthReactClient} = await import("../auth/betterAuthReactClient");
|
|
96
|
+
const {
|
|
97
|
+
completeBetterAuthOAuthHandoff,
|
|
98
|
+
createBetterAuthClient,
|
|
99
|
+
createStorageAdapter,
|
|
100
|
+
getBetterAuthBearerToken,
|
|
101
|
+
getBetterAuthClientWebAuth,
|
|
102
|
+
linkSocialWithHandoff,
|
|
103
|
+
repairCookieJar,
|
|
104
|
+
signInSocialWithHandoff,
|
|
105
|
+
withCookieJarRepair,
|
|
106
|
+
} = await import("../auth/betterAuthClient");
|
|
107
|
+
// The real, unmocked vanilla client: it runs captured options through Better Auth's own
|
|
108
|
+
// route proxy and better-fetch hook pipeline, so hook ordering is proven rather than assumed.
|
|
109
|
+
const {createAuthClient: createRealAuthClient} = await import("better-auth/client");
|
|
110
|
+
|
|
111
|
+
// Mirrors how @better-auth/expo reads its jar, so these tests fail if the plugin's
|
|
112
|
+
// throw-on-malformed-entry behaviour is ever reintroduced.
|
|
113
|
+
const readJarLikeExpoPlugin = (jar: string | null): string => {
|
|
114
|
+
return Object.entries(JSON.parse(jar ?? "{}")).reduce((acc, [key, value]) => {
|
|
115
|
+
const cookie = value as {expires?: string | null; value?: string};
|
|
116
|
+
if (cookie.expires && new Date(cookie.expires) < new Date()) {
|
|
117
|
+
return acc;
|
|
118
|
+
}
|
|
119
|
+
return acc ? `${acc}; ${key}=${cookie.value}` : `${key}=${cookie.value}`;
|
|
120
|
+
}, "");
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
describe("createStorageAdapter (web)", () => {
|
|
124
|
+
const globalWithWindow = globalThis as {window?: unknown};
|
|
125
|
+
const originalGet = AsyncStorage.getItem;
|
|
126
|
+
const originalSet = AsyncStorage.setItem;
|
|
127
|
+
const originalRemove = AsyncStorage.removeItem;
|
|
128
|
+
const calls = {get: [] as string[], remove: [] as string[], set: [] as Array<[string, string]>};
|
|
129
|
+
let originalWindow: unknown;
|
|
130
|
+
|
|
131
|
+
beforeEach(() => {
|
|
132
|
+
originalWindow = globalWithWindow.window;
|
|
133
|
+
calls.get = [];
|
|
134
|
+
calls.remove = [];
|
|
135
|
+
calls.set = [];
|
|
136
|
+
AsyncStorage.getItem = async (key: string): Promise<string | null> => {
|
|
137
|
+
calls.get.push(key);
|
|
138
|
+
return `async-${key}`;
|
|
139
|
+
};
|
|
140
|
+
AsyncStorage.setItem = async (key: string, value: string): Promise<void> => {
|
|
141
|
+
calls.set.push([key, value]);
|
|
142
|
+
};
|
|
143
|
+
AsyncStorage.removeItem = async (key: string): Promise<void> => {
|
|
144
|
+
calls.remove.push(key);
|
|
145
|
+
};
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
afterEach(() => {
|
|
149
|
+
AsyncStorage.getItem = originalGet;
|
|
150
|
+
AsyncStorage.setItem = originalSet;
|
|
151
|
+
AsyncStorage.removeItem = originalRemove;
|
|
152
|
+
if (typeof originalWindow === "undefined") {
|
|
153
|
+
delete globalWithWindow.window;
|
|
154
|
+
} else {
|
|
155
|
+
globalWithWindow.window = originalWindow;
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("reads, writes, and removes via AsyncStorage when window exists", async () => {
|
|
160
|
+
globalWithWindow.window = {};
|
|
161
|
+
const adapter = createStorageAdapter(true);
|
|
162
|
+
await expect(adapter.getItem("k")).resolves.toBe("async-k");
|
|
163
|
+
await adapter.setItem("a", "b");
|
|
164
|
+
await adapter.removeItem?.("c");
|
|
165
|
+
expect(calls.get).toEqual(["k"]);
|
|
166
|
+
expect(calls.set).toEqual([["a", "b"]]);
|
|
167
|
+
expect(calls.remove).toEqual(["c"]);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("returns null/void without touching AsyncStorage in SSR (no window)", async () => {
|
|
171
|
+
delete globalWithWindow.window;
|
|
172
|
+
const adapter = createStorageAdapter(true);
|
|
173
|
+
await expect(adapter.getItem("k")).resolves.toBeNull();
|
|
174
|
+
await expect(adapter.setItem("a", "b")).resolves.toBeUndefined();
|
|
175
|
+
await expect(adapter.removeItem?.("c")).resolves.toBeUndefined();
|
|
176
|
+
expect(calls.get).toEqual([]);
|
|
177
|
+
expect(calls.set).toEqual([]);
|
|
178
|
+
expect(calls.remove).toEqual([]);
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
describe("createStorageAdapter (native)", () => {
|
|
183
|
+
beforeEach(() => {
|
|
184
|
+
resetSecureCalls();
|
|
185
|
+
mockSecureStore();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("routes reads, writes, and deletes through SecureStore", () => {
|
|
189
|
+
const adapter = createStorageAdapter(false);
|
|
190
|
+
expect(adapter.getItem("auth")).toBe("secure-auth");
|
|
191
|
+
adapter.setItem("auth", "token");
|
|
192
|
+
void adapter.removeItem?.("auth");
|
|
193
|
+
expect(secureCalls.getSync).toEqual(["auth"]);
|
|
194
|
+
expect(secureCalls.setSync).toEqual([["auth", "token"]]);
|
|
195
|
+
expect(secureCalls.delete).toEqual(["auth"]);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// @better-auth/expo's client plugin reads the cookie jar synchronously
|
|
199
|
+
// (`getCookie(storage.getItem(name) || "{}")` then `JSON.parse`). A promise-returning
|
|
200
|
+
// getItem fails that parse, leaving an empty jar, so no `cookie` header is attached to
|
|
201
|
+
// native requests — the plugin also sets `credentials: "omit"`, making the stored
|
|
202
|
+
// cookie the only way a session reaches the server. The result was a login that
|
|
203
|
+
// succeeded and then bounced straight back to the login screen.
|
|
204
|
+
it("returns a string, not a promise, so the Expo plugin can parse the cookie jar", () => {
|
|
205
|
+
const adapter = createStorageAdapter(false);
|
|
206
|
+
const stored = adapter.getItem(`terreno-example_cookie`);
|
|
207
|
+
expect(stored).not.toBeInstanceOf(Promise);
|
|
208
|
+
expect(typeof stored).toBe("string");
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("writes synchronously so a cookie saved during sign-in is readable immediately", () => {
|
|
212
|
+
const adapter = createStorageAdapter(false);
|
|
213
|
+
adapter.setItem("terreno-example_cookie", '{"better-auth.session_token":{"value":"abc"}}');
|
|
214
|
+
expect(secureCalls.setSync).toEqual([
|
|
215
|
+
["terreno-example_cookie", '{"better-auth.session_token":{"value":"abc"}}'],
|
|
216
|
+
]);
|
|
217
|
+
expect(secureCalls.set).toEqual([]);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// @better-auth/expo 1.7 reads and writes through `getItemAsync` / `setItemAsync` on its
|
|
221
|
+
// serialized path; without them every request failed with "undefined is not a function".
|
|
222
|
+
it("provides the async pair the 1.7 Expo plugin calls", async () => {
|
|
223
|
+
const adapter = createStorageAdapter(false);
|
|
224
|
+
|
|
225
|
+
expect(await adapter.getItemAsync?.("auth")).toBe("secure-auth");
|
|
226
|
+
await adapter.setItemAsync?.("auth", "token");
|
|
227
|
+
|
|
228
|
+
expect(secureCalls.get).toEqual(["auth"]);
|
|
229
|
+
expect(secureCalls.set).toEqual([["auth", "token"]]);
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
describe("repairCookieJar", () => {
|
|
234
|
+
it("drops the null entry that made every native request throw", () => {
|
|
235
|
+
expect(() => readJarLikeExpoPlugin(CORRUPT_JAR)).toThrow();
|
|
236
|
+
|
|
237
|
+
const repaired = repairCookieJar(CORRUPT_JAR);
|
|
238
|
+
|
|
239
|
+
expect(() => readJarLikeExpoPlugin(repaired)).not.toThrow();
|
|
240
|
+
expect(JSON.parse(repaired ?? "{}")).toEqual({
|
|
241
|
+
"better-auth.session_data": {expires: null, value: "cached"},
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("leaves a healthy jar byte-identical", () => {
|
|
246
|
+
const jar = JSON.stringify({
|
|
247
|
+
"better-auth.session_token": {expires: null, value: "abc"},
|
|
248
|
+
});
|
|
249
|
+
expect(repairCookieJar(jar)).toBe(jar);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("empties a jar that is not an object, which would throw in Object.entries", () => {
|
|
253
|
+
expect(repairCookieJar("null")).toBeNull();
|
|
254
|
+
expect(repairCookieJar("7")).toBeNull();
|
|
255
|
+
expect(repairCookieJar('["a"]')).toBeNull();
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
it("passes through empty and unparseable values the plugin already tolerates", () => {
|
|
259
|
+
expect(repairCookieJar(null)).toBeNull();
|
|
260
|
+
expect(repairCookieJar("")).toBe("");
|
|
261
|
+
expect(repairCookieJar("not json")).toBe("not json");
|
|
262
|
+
});
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
describe("withCookieJarRepair", () => {
|
|
266
|
+
it("repairs the jar key and leaves other keys untouched", () => {
|
|
267
|
+
const sessionCache = JSON.stringify({expiresAt: 1785217980921, signature: "sig"});
|
|
268
|
+
const storage = withCookieJarRepair({
|
|
269
|
+
cookieJarKey: "terreno_cookie",
|
|
270
|
+
storage: {
|
|
271
|
+
getItem: (key: string) => (key === "terreno_cookie" ? CORRUPT_JAR : sessionCache),
|
|
272
|
+
setItem: () => {},
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
expect(JSON.parse((storage.getItem("terreno_cookie") as string) ?? "{}")).toEqual({
|
|
277
|
+
"better-auth.session_data": {expires: null, value: "cached"},
|
|
278
|
+
});
|
|
279
|
+
// The cached session payload holds plain numbers and strings, so repairing it would strip it.
|
|
280
|
+
expect(storage.getItem("terreno_session_data")).toBe(sessionCache);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it("repairs the jar on the async read the 1.7 plugin uses, and passes other keys through", async () => {
|
|
284
|
+
const storage = withCookieJarRepair({
|
|
285
|
+
cookieJarKey: "terreno_cookie",
|
|
286
|
+
storage: {
|
|
287
|
+
getItem: () => null,
|
|
288
|
+
getItemAsync: async (key: string) => (key === "terreno_cookie" ? CORRUPT_JAR : "plain"),
|
|
289
|
+
setItem: () => {},
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
const repaired = await storage.getItemAsync?.("terreno_cookie");
|
|
294
|
+
|
|
295
|
+
expect(JSON.parse((repaired as string) ?? "{}")).toEqual({
|
|
296
|
+
"better-auth.session_data": {expires: null, value: "cached"},
|
|
297
|
+
});
|
|
298
|
+
expect(await storage.getItemAsync?.("terreno_session_data")).toBe("plain");
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it("adds no async read when the storage has none", () => {
|
|
302
|
+
const storage = withCookieJarRepair({
|
|
303
|
+
cookieJarKey: "terreno_cookie",
|
|
304
|
+
storage: {getItem: () => null, setItem: () => {}},
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
expect(storage.getItemAsync).toBeUndefined();
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("repairs promise-shaped reads from the web adapter", async () => {
|
|
311
|
+
const storage = withCookieJarRepair({
|
|
312
|
+
cookieJarKey: "terreno_cookie",
|
|
313
|
+
storage: {
|
|
314
|
+
getItem: () => Promise.resolve(CORRUPT_JAR),
|
|
315
|
+
setItem: () => {},
|
|
316
|
+
},
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
const repaired = await storage.getItem("terreno_cookie");
|
|
320
|
+
|
|
321
|
+
expect(JSON.parse((repaired as string) ?? "{}")).toEqual({
|
|
322
|
+
"better-auth.session_data": {expires: null, value: "cached"},
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
interface BearerFetchOptions {
|
|
328
|
+
auth: {token: () => string | null; type: string};
|
|
329
|
+
credentials: string;
|
|
330
|
+
onRequest: (context: {headers: Headers; url: string | URL}) => unknown;
|
|
331
|
+
onResponse: (context: {request: {url: string | URL}; response: Response}) => unknown;
|
|
332
|
+
onSuccess: (context: {
|
|
333
|
+
data: unknown;
|
|
334
|
+
request: {headers: Headers; url: string | URL};
|
|
335
|
+
response: Response;
|
|
336
|
+
}) => Promise<void> | void;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
interface MemoryStorage {
|
|
340
|
+
getItem: (key: string) => string | null;
|
|
341
|
+
removeItem: (key: string) => void;
|
|
342
|
+
setItem: (key: string, value: string) => void;
|
|
343
|
+
values: Map<string, string>;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const createMemoryStorage = (initial: Record<string, string> = {}): MemoryStorage => {
|
|
347
|
+
const values = new Map(Object.entries(initial));
|
|
348
|
+
return {
|
|
349
|
+
getItem: (key: string): string | null => values.get(key) ?? null,
|
|
350
|
+
removeItem: (key: string): void => {
|
|
351
|
+
values.delete(key);
|
|
352
|
+
},
|
|
353
|
+
setItem: (key: string, value: string): void => {
|
|
354
|
+
values.set(key, value);
|
|
355
|
+
},
|
|
356
|
+
values,
|
|
357
|
+
};
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
interface SentRequest {
|
|
361
|
+
authorization: string | null;
|
|
362
|
+
credentials: RequestCredentials | undefined;
|
|
363
|
+
pathname: string;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
type FakeServer = (pathname: string) => Response | Promise<Response>;
|
|
367
|
+
|
|
368
|
+
const jsonResponse = (body: unknown, init: ResponseInit = {}): Response => {
|
|
369
|
+
return new Response(JSON.stringify(body), {
|
|
370
|
+
...init,
|
|
371
|
+
headers: {"content-type": "application/json", ...(init.headers ?? {})},
|
|
372
|
+
});
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
// Builds the real Better Auth client from the options createBetterAuthClient handed to
|
|
376
|
+
// createAuthClient, with fetch replaced by a fake server, and records what each call sent.
|
|
377
|
+
const driveCapturedClient = (
|
|
378
|
+
server: FakeServer
|
|
379
|
+
): {client: ReturnType<typeof createRealAuthClient>; sent: SentRequest[]} => {
|
|
380
|
+
const sent: SentRequest[] = [];
|
|
381
|
+
const options = captured.auth as {baseURL: string; fetchOptions: Record<string, unknown>};
|
|
382
|
+
const customFetchImpl = async (
|
|
383
|
+
input: string | URL | Request,
|
|
384
|
+
init?: RequestInit
|
|
385
|
+
): Promise<Response> => {
|
|
386
|
+
const {pathname} = new URL(input instanceof Request ? input.url : input.toString());
|
|
387
|
+
sent.push({
|
|
388
|
+
authorization: new Headers(init?.headers).get("authorization"),
|
|
389
|
+
credentials: init?.credentials,
|
|
390
|
+
pathname,
|
|
391
|
+
});
|
|
392
|
+
return server(pathname);
|
|
393
|
+
};
|
|
394
|
+
const client = createRealAuthClient({
|
|
395
|
+
baseURL: options.baseURL,
|
|
396
|
+
fetchOptions: {...options.fetchOptions, customFetchImpl},
|
|
397
|
+
});
|
|
398
|
+
return {client, sent};
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
const bearerOptions = (): BearerFetchOptions => {
|
|
402
|
+
return (captured.auth as {fetchOptions: BearerFetchOptions}).fetchOptions;
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
describe("createBetterAuthClient with webAuth bearer on web", () => {
|
|
406
|
+
const globalWithWindow = globalThis as {window?: unknown};
|
|
407
|
+
const hadWindow = "window" in globalWithWindow;
|
|
408
|
+
const originalWindow = globalWithWindow.window;
|
|
409
|
+
|
|
410
|
+
beforeEach(() => {
|
|
411
|
+
captured.auth = null;
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
afterEach(() => {
|
|
415
|
+
if (hadWindow) {
|
|
416
|
+
globalWithWindow.window = originalWindow;
|
|
417
|
+
} else {
|
|
418
|
+
delete globalWithWindow.window;
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it("reports a client's web auth mode and its stored bearer token", () => {
|
|
423
|
+
const bearerStorage = createMemoryStorage();
|
|
424
|
+
const bearerClient = createBetterAuthClient({
|
|
425
|
+
baseURL: "http://localhost:3000",
|
|
426
|
+
bearerStorage,
|
|
427
|
+
scheme: "terreno",
|
|
428
|
+
storagePrefix: "app",
|
|
429
|
+
webAuth: "bearer",
|
|
430
|
+
});
|
|
431
|
+
expect(getBetterAuthClientWebAuth(bearerClient)).toEqual({
|
|
432
|
+
bearerToken: null,
|
|
433
|
+
webAuth: "bearer",
|
|
434
|
+
});
|
|
435
|
+
bearerStorage.setItem("app_bearer_token", "t9");
|
|
436
|
+
expect(getBetterAuthClientWebAuth(bearerClient)).toEqual({
|
|
437
|
+
bearerToken: "t9",
|
|
438
|
+
webAuth: "bearer",
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
const cookieClient = createBetterAuthClient({
|
|
442
|
+
baseURL: "http://localhost:3000",
|
|
443
|
+
scheme: "terreno",
|
|
444
|
+
});
|
|
445
|
+
expect(getBetterAuthClientWebAuth(cookieClient)).toEqual({
|
|
446
|
+
bearerToken: null,
|
|
447
|
+
webAuth: "cookie",
|
|
448
|
+
});
|
|
449
|
+
// A client createBetterAuthClient did not make is treated as cookie mode.
|
|
450
|
+
expect(getBetterAuthClientWebAuth({})).toEqual({bearerToken: null, webAuth: "cookie"});
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
it("stores set-auth-token in localStorage, sends it as the bearer, and omits cookies", async () => {
|
|
454
|
+
const localStorage = createMemoryStorage();
|
|
455
|
+
globalWithWindow.window = {localStorage};
|
|
456
|
+
createBetterAuthClient({
|
|
457
|
+
baseURL: "http://localhost:3000",
|
|
458
|
+
scheme: "terreno",
|
|
459
|
+
webAuth: "bearer",
|
|
460
|
+
});
|
|
461
|
+
const options = bearerOptions();
|
|
462
|
+
|
|
463
|
+
await options.onSuccess({
|
|
464
|
+
data: {token: "t1"},
|
|
465
|
+
request: {headers: new Headers(), url: "http://localhost:3000/api/auth/sign-in/email"},
|
|
466
|
+
response: new Response(null, {headers: {"set-auth-token": "t1"}}),
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
expect(localStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
470
|
+
expect(options.auth.type).toBe("Bearer");
|
|
471
|
+
expect(options.auth.token()).toBe("t1");
|
|
472
|
+
expect(getBetterAuthBearerToken()).toBe("t1");
|
|
473
|
+
expect(options.credentials).toBe("omit");
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
it("sends the stored token on getSession through the real client, with no cookies", async () => {
|
|
477
|
+
const bearerStorage = createMemoryStorage();
|
|
478
|
+
createBetterAuthClient({
|
|
479
|
+
baseURL: "http://localhost:3000",
|
|
480
|
+
bearerStorage,
|
|
481
|
+
scheme: "terreno",
|
|
482
|
+
webAuth: "bearer",
|
|
483
|
+
});
|
|
484
|
+
const {client, sent} = driveCapturedClient((pathname) => {
|
|
485
|
+
if (pathname.endsWith("/sign-in/email")) {
|
|
486
|
+
return jsonResponse({token: "t1"}, {headers: {"set-auth-token": "t1"}});
|
|
487
|
+
}
|
|
488
|
+
return jsonResponse({session: {id: "s1"}, user: {id: "u1"}});
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
await client.signIn.email({email: "a@example.com", password: "password123"});
|
|
492
|
+
await client.getSession();
|
|
493
|
+
|
|
494
|
+
expect(sent.map((request) => request.credentials)).toEqual(["omit", "omit"]);
|
|
495
|
+
expect(sent[0].authorization).toBeNull();
|
|
496
|
+
expect(sent[1]).toEqual({
|
|
497
|
+
authorization: "Bearer t1",
|
|
498
|
+
credentials: "omit",
|
|
499
|
+
pathname: "/api/auth/get-session",
|
|
500
|
+
});
|
|
501
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
it("clears the token on sign-out even when the request returns 5xx", async () => {
|
|
505
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
506
|
+
createBetterAuthClient({
|
|
507
|
+
baseURL: "http://localhost:3000",
|
|
508
|
+
bearerStorage,
|
|
509
|
+
scheme: "terreno",
|
|
510
|
+
webAuth: "bearer",
|
|
511
|
+
});
|
|
512
|
+
let storedWhenSent: string | null | undefined;
|
|
513
|
+
const {client, sent} = driveCapturedClient(() => {
|
|
514
|
+
storedWhenSent = bearerStorage.getItem("terreno_bearer_token");
|
|
515
|
+
return jsonResponse({message: "down"}, {status: 503});
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
const result = await client.signOut();
|
|
519
|
+
|
|
520
|
+
expect(result.error?.status).toBe(503);
|
|
521
|
+
// The request still carries the token so the server can revoke the session, but the
|
|
522
|
+
// device has already forgotten it.
|
|
523
|
+
expect(sent[0].authorization).toBe("Bearer t1");
|
|
524
|
+
expect(storedWhenSent).toBeNull();
|
|
525
|
+
expect(bearerStorage.values.has("terreno_bearer_token")).toBe(false);
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
it("clears the token on sign-out even when the request never reaches the server", async () => {
|
|
529
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
530
|
+
createBetterAuthClient({
|
|
531
|
+
baseURL: "http://localhost:3000",
|
|
532
|
+
bearerStorage,
|
|
533
|
+
scheme: "terreno",
|
|
534
|
+
webAuth: "bearer",
|
|
535
|
+
});
|
|
536
|
+
const {client} = driveCapturedClient(() => {
|
|
537
|
+
throw new TypeError("Failed to fetch");
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
await expect(client.signOut()).rejects.toThrow("Failed to fetch");
|
|
541
|
+
expect(bearerStorage.values.has("terreno_bearer_token")).toBe(false);
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
it("drops a token issued by a request that was in flight across a sign-out", async () => {
|
|
545
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
546
|
+
createBetterAuthClient({
|
|
547
|
+
baseURL: "http://localhost:3000",
|
|
548
|
+
bearerStorage,
|
|
549
|
+
scheme: "terreno",
|
|
550
|
+
webAuth: "bearer",
|
|
551
|
+
});
|
|
552
|
+
let releaseSession: (response: Response) => void = () => {};
|
|
553
|
+
const {client} = driveCapturedClient((pathname) => {
|
|
554
|
+
if (pathname.endsWith("/get-session")) {
|
|
555
|
+
return new Promise<Response>((resolve) => {
|
|
556
|
+
releaseSession = resolve;
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
throw new TypeError("Failed to fetch");
|
|
560
|
+
});
|
|
561
|
+
|
|
562
|
+
const pendingSession = client.getSession();
|
|
563
|
+
await expect(client.signOut()).rejects.toThrow("Failed to fetch");
|
|
564
|
+
// The session refresh lands after the failed sign-out and re-issues the token.
|
|
565
|
+
releaseSession(
|
|
566
|
+
jsonResponse({session: {id: "s1"}, user: {id: "u1"}}, {headers: {"set-auth-token": "t1"}})
|
|
567
|
+
);
|
|
568
|
+
await pendingSession;
|
|
569
|
+
|
|
570
|
+
expect(bearerStorage.values.has("terreno_bearer_token")).toBe(false);
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
it("clears the token after a successful getSession with no session", async () => {
|
|
574
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
575
|
+
createBetterAuthClient({
|
|
576
|
+
baseURL: "http://localhost:3000",
|
|
577
|
+
bearerStorage,
|
|
578
|
+
scheme: "terreno",
|
|
579
|
+
webAuth: "bearer",
|
|
580
|
+
});
|
|
581
|
+
const {client, sent} = driveCapturedClient(() => jsonResponse(null));
|
|
582
|
+
|
|
583
|
+
await client.getSession();
|
|
584
|
+
|
|
585
|
+
expect(sent[0].authorization).toBe("Bearer t1");
|
|
586
|
+
expect(bearerStorage.values.has("terreno_bearer_token")).toBe(false);
|
|
587
|
+
});
|
|
588
|
+
|
|
589
|
+
it("keeps a newer token stored while a getSession with no session was in flight", async () => {
|
|
590
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
591
|
+
createBetterAuthClient({
|
|
592
|
+
baseURL: "http://localhost:3000",
|
|
593
|
+
bearerStorage,
|
|
594
|
+
scheme: "terreno",
|
|
595
|
+
webAuth: "bearer",
|
|
596
|
+
});
|
|
597
|
+
const {client} = driveCapturedClient(() => {
|
|
598
|
+
// A sign-in that finished while this read was in flight.
|
|
599
|
+
bearerStorage.setItem("terreno_bearer_token", "t2");
|
|
600
|
+
return jsonResponse(null);
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
await client.getSession();
|
|
604
|
+
|
|
605
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t2");
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
it("keeps a sign-in's token when a signed-out getSession started before it", async () => {
|
|
609
|
+
const bearerStorage = createMemoryStorage();
|
|
610
|
+
createBetterAuthClient({
|
|
611
|
+
baseURL: "http://localhost:3000",
|
|
612
|
+
bearerStorage,
|
|
613
|
+
scheme: "terreno",
|
|
614
|
+
webAuth: "bearer",
|
|
615
|
+
});
|
|
616
|
+
const {client, sent} = driveCapturedClient(() => {
|
|
617
|
+
bearerStorage.setItem("terreno_bearer_token", "t1");
|
|
618
|
+
return jsonResponse(null);
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
await client.getSession();
|
|
622
|
+
|
|
623
|
+
expect(sent[0].authorization).toBeNull();
|
|
624
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
it("leaves the token alone on other successful calls that issue none", async () => {
|
|
628
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
629
|
+
createBetterAuthClient({
|
|
630
|
+
baseURL: "http://localhost:3000",
|
|
631
|
+
bearerStorage,
|
|
632
|
+
scheme: "terreno",
|
|
633
|
+
webAuth: "bearer",
|
|
634
|
+
});
|
|
635
|
+
const {client, sent} = driveCapturedClient(() => jsonResponse({status: true}));
|
|
636
|
+
|
|
637
|
+
await client.updateUser({name: "New Name"});
|
|
638
|
+
|
|
639
|
+
expect(sent[0]).toEqual({
|
|
640
|
+
authorization: "Bearer t1",
|
|
641
|
+
credentials: "omit",
|
|
642
|
+
pathname: "/api/auth/update-user",
|
|
643
|
+
});
|
|
644
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
645
|
+
});
|
|
646
|
+
|
|
647
|
+
it("keeps the token when getSession errors, returns 5xx, or returns a session", async () => {
|
|
648
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
649
|
+
createBetterAuthClient({
|
|
650
|
+
baseURL: "http://localhost:3000",
|
|
651
|
+
bearerStorage,
|
|
652
|
+
scheme: "terreno",
|
|
653
|
+
webAuth: "bearer",
|
|
654
|
+
});
|
|
655
|
+
const responses: Array<() => Response> = [
|
|
656
|
+
(): Response => jsonResponse({message: "down"}, {status: 500}),
|
|
657
|
+
(): Response => {
|
|
658
|
+
throw new TypeError("Failed to fetch");
|
|
659
|
+
},
|
|
660
|
+
(): Response => jsonResponse({session: {id: "s1"}, user: {id: "u1"}}),
|
|
661
|
+
];
|
|
662
|
+
const {client} = driveCapturedClient(() => {
|
|
663
|
+
const next = responses.shift();
|
|
664
|
+
if (!next) {
|
|
665
|
+
throw new Error("unexpected request");
|
|
666
|
+
}
|
|
667
|
+
return next();
|
|
668
|
+
});
|
|
669
|
+
|
|
670
|
+
const failed = await client.getSession();
|
|
671
|
+
await expect(client.getSession()).rejects.toThrow("Failed to fetch");
|
|
672
|
+
await client.getSession();
|
|
673
|
+
|
|
674
|
+
expect(failed.error?.status).toBe(500);
|
|
675
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
it("uses a custom bearerStorage instead of localStorage", async () => {
|
|
679
|
+
const localStorage = createMemoryStorage();
|
|
680
|
+
globalWithWindow.window = {localStorage};
|
|
681
|
+
const bearerStorage = createMemoryStorage();
|
|
682
|
+
createBetterAuthClient({
|
|
683
|
+
baseURL: "http://localhost:3000",
|
|
684
|
+
bearerStorage,
|
|
685
|
+
scheme: "terreno",
|
|
686
|
+
storagePrefix: "custom",
|
|
687
|
+
webAuth: "bearer",
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
await bearerOptions().onSuccess({
|
|
691
|
+
data: {token: "t1"},
|
|
692
|
+
request: {headers: new Headers(), url: "http://localhost:3000/api/auth/sign-in/email"},
|
|
693
|
+
response: new Response(null, {headers: {"set-auth-token": "t1"}}),
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
expect(bearerStorage.values.get("custom_bearer_token")).toBe("t1");
|
|
697
|
+
expect(localStorage.values.size).toBe(0);
|
|
698
|
+
expect(getBetterAuthBearerToken({bearerStorage, storagePrefix: "custom"})).toBe("t1");
|
|
699
|
+
expect(getBetterAuthBearerToken({storagePrefix: "custom"})).toBeNull();
|
|
700
|
+
});
|
|
701
|
+
|
|
702
|
+
it("finds localStorage when the client was created before window existed", async () => {
|
|
703
|
+
delete globalWithWindow.window;
|
|
704
|
+
createBetterAuthClient({
|
|
705
|
+
baseURL: "http://localhost:3000",
|
|
706
|
+
scheme: "terreno",
|
|
707
|
+
webAuth: "bearer",
|
|
708
|
+
});
|
|
709
|
+
const localStorage = createMemoryStorage();
|
|
710
|
+
globalWithWindow.window = {localStorage};
|
|
711
|
+
|
|
712
|
+
await bearerOptions().onSuccess({
|
|
713
|
+
data: {token: "t1"},
|
|
714
|
+
request: {headers: new Headers(), url: "http://localhost:3000/api/auth/sign-in/email"},
|
|
715
|
+
response: new Response(null, {headers: {"set-auth-token": "t1"}}),
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
expect(localStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
it("reads no token when there is no window or localStorage", () => {
|
|
722
|
+
delete globalWithWindow.window;
|
|
723
|
+
expect(getBetterAuthBearerToken()).toBeNull();
|
|
724
|
+
globalWithWindow.window = {
|
|
725
|
+
get localStorage(): never {
|
|
726
|
+
throw new Error("SecurityError: storage is blocked");
|
|
727
|
+
},
|
|
728
|
+
};
|
|
729
|
+
expect(getBetterAuthBearerToken()).toBeNull();
|
|
730
|
+
});
|
|
731
|
+
});
|
|
732
|
+
|
|
733
|
+
const CHALLENGE_HEADER = "X-Terreno-Auth-Challenge";
|
|
734
|
+
const CHALLENGE_KEY = "terreno_auth_challenge";
|
|
735
|
+
const TWO_FACTOR = "better-auth.two_factor";
|
|
736
|
+
const TRUST_DEVICE = "better-auth.trust_device";
|
|
737
|
+
const PASSKEY = "better-auth.better-auth-passkey";
|
|
738
|
+
const DONT_REMEMBER = "better-auth.dont_remember";
|
|
739
|
+
|
|
740
|
+
interface ChallengeRequest {
|
|
741
|
+
challenge: string | null;
|
|
742
|
+
pathname: string;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// Loose view of the real client the challenge tests drive.
|
|
746
|
+
interface ChallengeClient {
|
|
747
|
+
getSession: () => Promise<unknown>;
|
|
748
|
+
passkey: {listUserPasskeys: () => Promise<unknown>};
|
|
749
|
+
signIn: {
|
|
750
|
+
email: (body: {email: string; password: string}) => Promise<unknown>;
|
|
751
|
+
passkey: () => Promise<unknown>;
|
|
752
|
+
};
|
|
753
|
+
signOut: () => Promise<unknown>;
|
|
754
|
+
twoFactor: {verifyTotp: (body: {code: string; trustDevice?: boolean}) => Promise<unknown>};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const challengeHeader = (pairs: Record<string, string>): Record<string, string> => ({
|
|
758
|
+
[CHALLENGE_HEADER]: new URLSearchParams(pairs).toString(),
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
// Creates a web bearer client with the 2FA and passkey plugins, backed by a fake server, and
|
|
762
|
+
// records the challenge header each call sent.
|
|
763
|
+
const createChallengeClient = (
|
|
764
|
+
bearerStorage: MemoryStorage,
|
|
765
|
+
server: FakeServer
|
|
766
|
+
): {client: ChallengeClient; sent: ChallengeRequest[]} => {
|
|
767
|
+
const sent: ChallengeRequest[] = [];
|
|
768
|
+
captured.build = (config: Record<string, unknown>): unknown => {
|
|
769
|
+
const customFetchImpl = async (input: string | URL, init?: RequestInit): Promise<Response> => {
|
|
770
|
+
const {pathname} = new URL(input.toString());
|
|
771
|
+
sent.push({challenge: new Headers(init?.headers).get(CHALLENGE_HEADER), pathname});
|
|
772
|
+
return server(pathname);
|
|
773
|
+
};
|
|
774
|
+
return createRealAuthClient({
|
|
775
|
+
baseURL: config.baseURL as string,
|
|
776
|
+
fetchOptions: {
|
|
777
|
+
...(config.fetchOptions as Record<string, unknown>),
|
|
778
|
+
customFetchImpl: customFetchImpl as never,
|
|
779
|
+
},
|
|
780
|
+
plugins: config.plugins as never,
|
|
781
|
+
});
|
|
782
|
+
};
|
|
783
|
+
const client = createBetterAuthClient({
|
|
784
|
+
baseURL: "http://localhost:4000",
|
|
785
|
+
bearerStorage,
|
|
786
|
+
features: {passkey: true, twoFactor: true},
|
|
787
|
+
scheme: "terreno",
|
|
788
|
+
webAuth: "bearer",
|
|
789
|
+
}) as unknown as ChallengeClient;
|
|
790
|
+
return {client, sent};
|
|
791
|
+
};
|
|
792
|
+
|
|
793
|
+
const heldChallenge = (bearerStorage: MemoryStorage): Record<string, string> =>
|
|
794
|
+
Object.fromEntries(new URLSearchParams(bearerStorage.values.get(CHALLENGE_KEY) ?? ""));
|
|
795
|
+
|
|
796
|
+
describe("cookie-free challenges in web bearer mode", () => {
|
|
797
|
+
beforeEach(() => {
|
|
798
|
+
captured.auth = null;
|
|
799
|
+
captured.build = null;
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
afterEach(() => {
|
|
803
|
+
captured.build = null;
|
|
804
|
+
});
|
|
805
|
+
|
|
806
|
+
it("stores the challenge from sign-in and sends it on verify, opting in when none is held", async () => {
|
|
807
|
+
const bearerStorage = createMemoryStorage();
|
|
808
|
+
const {client, sent} = createChallengeClient(bearerStorage, (pathname) => {
|
|
809
|
+
if (pathname.endsWith("/sign-in/email")) {
|
|
810
|
+
return jsonResponse(
|
|
811
|
+
{twoFactorMethods: ["totp"], twoFactorRedirect: true},
|
|
812
|
+
{headers: challengeHeader({[TWO_FACTOR]: "2fa-id.sig"})}
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
return jsonResponse({token: "t1"}, {headers: {"set-auth-token": "t1"}});
|
|
816
|
+
});
|
|
817
|
+
|
|
818
|
+
await client.signIn.email({email: "a@example.com", password: "secret"});
|
|
819
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TWO_FACTOR]: "2fa-id.sig"});
|
|
820
|
+
await client.twoFactor.verifyTotp({code: "123456"});
|
|
821
|
+
|
|
822
|
+
expect(sent).toEqual([
|
|
823
|
+
{challenge: "-", pathname: "/api/auth/sign-in/email"},
|
|
824
|
+
{
|
|
825
|
+
challenge: new URLSearchParams({[TWO_FACTOR]: "2fa-id.sig"}).toString(),
|
|
826
|
+
pathname: "/api/auth/two-factor/verify-totp",
|
|
827
|
+
},
|
|
828
|
+
]);
|
|
829
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t1");
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
it("keeps the stored token when a sign-in answers with a two-factor redirect", async () => {
|
|
833
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t0"});
|
|
834
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
835
|
+
jsonResponse(
|
|
836
|
+
{twoFactorMethods: ["totp"], twoFactorRedirect: true},
|
|
837
|
+
{headers: {...challengeHeader({[TWO_FACTOR]: "2fa.sig"}), "set-auth-token": "dead"}}
|
|
838
|
+
)
|
|
839
|
+
);
|
|
840
|
+
|
|
841
|
+
await client.signIn.email({email: "a@example.com", password: "secret"});
|
|
842
|
+
|
|
843
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t0");
|
|
844
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TWO_FACTOR]: "2fa.sig"});
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
it("drops dont_remember with the two-factor challenge after a successful verify", async () => {
|
|
848
|
+
const bearerStorage = createMemoryStorage({
|
|
849
|
+
[CHALLENGE_KEY]: new URLSearchParams({
|
|
850
|
+
[DONT_REMEMBER]: "true.sig",
|
|
851
|
+
[TRUST_DEVICE]: "trust.sig",
|
|
852
|
+
[TWO_FACTOR]: "2fa.sig",
|
|
853
|
+
}).toString(),
|
|
854
|
+
});
|
|
855
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
856
|
+
jsonResponse({token: "t1"}, {headers: {"set-auth-token": "t1"}})
|
|
857
|
+
);
|
|
858
|
+
|
|
859
|
+
await client.twoFactor.verifyTotp({code: "123456"});
|
|
860
|
+
|
|
861
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TRUST_DEVICE]: "trust.sig"});
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
it("sends the challenge only on two-factor, passkey, and sign-in calls", async () => {
|
|
865
|
+
const bearerStorage = createMemoryStorage({[CHALLENGE_KEY]: `${TRUST_DEVICE}=trust.sig`});
|
|
866
|
+
const {client, sent} = createChallengeClient(bearerStorage, () => jsonResponse({}));
|
|
867
|
+
|
|
868
|
+
await client.getSession();
|
|
869
|
+
await client.passkey.listUserPasskeys();
|
|
870
|
+
await client.signOut();
|
|
871
|
+
|
|
872
|
+
expect(sent).toEqual([
|
|
873
|
+
{challenge: null, pathname: "/api/auth/get-session"},
|
|
874
|
+
{challenge: `${TRUST_DEVICE}=trust.sig`, pathname: "/api/auth/passkey/list-user-passkeys"},
|
|
875
|
+
{challenge: null, pathname: "/api/auth/sign-out"},
|
|
876
|
+
]);
|
|
877
|
+
});
|
|
878
|
+
|
|
879
|
+
it("clears the two-factor challenge after a successful verify and keeps the trusted device", async () => {
|
|
880
|
+
const bearerStorage = createMemoryStorage({[CHALLENGE_KEY]: `${TWO_FACTOR}=2fa-id.sig`});
|
|
881
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
882
|
+
jsonResponse(
|
|
883
|
+
{token: "t1"},
|
|
884
|
+
{headers: {...challengeHeader({[TRUST_DEVICE]: "trust.sig"}), "set-auth-token": "t1"}}
|
|
885
|
+
)
|
|
886
|
+
);
|
|
887
|
+
|
|
888
|
+
await client.twoFactor.verifyTotp({code: "123456", trustDevice: true});
|
|
889
|
+
|
|
890
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TRUST_DEVICE]: "trust.sig"});
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
it("keeps the two-factor challenge when verify fails, so the user can retry", async () => {
|
|
894
|
+
const bearerStorage = createMemoryStorage({[CHALLENGE_KEY]: `${TWO_FACTOR}=2fa-id.sig`});
|
|
895
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
896
|
+
jsonResponse({code: "INVALID_CODE"}, {status: 401})
|
|
897
|
+
);
|
|
898
|
+
|
|
899
|
+
await client.twoFactor.verifyTotp({code: "000000"});
|
|
900
|
+
|
|
901
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TWO_FACTOR]: "2fa-id.sig"});
|
|
902
|
+
});
|
|
903
|
+
|
|
904
|
+
it("forgets a challenge the server expires, even on an error response", async () => {
|
|
905
|
+
const bearerStorage = createMemoryStorage({
|
|
906
|
+
[CHALLENGE_KEY]: new URLSearchParams({
|
|
907
|
+
[TRUST_DEVICE]: "t.sig",
|
|
908
|
+
[TWO_FACTOR]: "2fa.sig",
|
|
909
|
+
}).toString(),
|
|
910
|
+
});
|
|
911
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
912
|
+
jsonResponse(
|
|
913
|
+
{code: "TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE"},
|
|
914
|
+
{headers: challengeHeader({[TWO_FACTOR]: ""}), status: 400}
|
|
915
|
+
)
|
|
916
|
+
);
|
|
917
|
+
|
|
918
|
+
await client.twoFactor.verifyTotp({code: "000000"});
|
|
919
|
+
|
|
920
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TRUST_DEVICE]: "t.sig"});
|
|
921
|
+
});
|
|
922
|
+
|
|
923
|
+
it("replaces a rotated trust value and removes the key when nothing is left", async () => {
|
|
924
|
+
const bearerStorage = createMemoryStorage({[CHALLENGE_KEY]: `${TRUST_DEVICE}=old.sig`});
|
|
925
|
+
let header: Record<string, string> = challengeHeader({[TRUST_DEVICE]: "new.sig"});
|
|
926
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
927
|
+
jsonResponse({token: "t1"}, {headers: {...header, "set-auth-token": "t1"}})
|
|
928
|
+
);
|
|
929
|
+
|
|
930
|
+
await client.signIn.email({email: "a@example.com", password: "secret"});
|
|
931
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TRUST_DEVICE]: "new.sig"});
|
|
932
|
+
|
|
933
|
+
header = challengeHeader({[TRUST_DEVICE]: ""});
|
|
934
|
+
await client.signIn.email({email: "a@example.com", password: "secret"});
|
|
935
|
+
expect(bearerStorage.values.has(CHALLENGE_KEY)).toBe(false);
|
|
936
|
+
});
|
|
937
|
+
|
|
938
|
+
it("drops pending challenges on sign-out but keeps the trusted device", async () => {
|
|
939
|
+
const bearerStorage = createMemoryStorage({
|
|
940
|
+
[CHALLENGE_KEY]: new URLSearchParams({
|
|
941
|
+
[PASSKEY]: "pk.sig",
|
|
942
|
+
[TRUST_DEVICE]: "trust.sig",
|
|
943
|
+
[TWO_FACTOR]: "2fa.sig",
|
|
944
|
+
}).toString(),
|
|
945
|
+
terreno_bearer_token: "t1",
|
|
946
|
+
});
|
|
947
|
+
const {client} = createChallengeClient(bearerStorage, () =>
|
|
948
|
+
jsonResponse({message: "down"}, {status: 503})
|
|
949
|
+
);
|
|
950
|
+
|
|
951
|
+
await client.signOut();
|
|
952
|
+
|
|
953
|
+
expect(heldChallenge(bearerStorage)).toEqual({[TRUST_DEVICE]: "trust.sig"});
|
|
954
|
+
expect(bearerStorage.values.has("terreno_bearer_token")).toBe(false);
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
it("removes the challenge key on sign-out when nothing is trusted", async () => {
|
|
958
|
+
const bearerStorage = createMemoryStorage({[CHALLENGE_KEY]: `${TWO_FACTOR}=2fa.sig`});
|
|
959
|
+
const {client} = createChallengeClient(bearerStorage, () => jsonResponse({success: true}));
|
|
960
|
+
|
|
961
|
+
await client.signOut();
|
|
962
|
+
|
|
963
|
+
expect(bearerStorage.values.has(CHALLENGE_KEY)).toBe(false);
|
|
964
|
+
});
|
|
965
|
+
|
|
966
|
+
it("stores the passkey challenge under a custom storagePrefix", async () => {
|
|
967
|
+
const bearerStorage = createMemoryStorage();
|
|
968
|
+
const sent: ChallengeRequest[] = [];
|
|
969
|
+
captured.build = (config: Record<string, unknown>): unknown =>
|
|
970
|
+
createRealAuthClient({
|
|
971
|
+
baseURL: config.baseURL as string,
|
|
972
|
+
fetchOptions: {
|
|
973
|
+
...(config.fetchOptions as Record<string, unknown>),
|
|
974
|
+
customFetchImpl: (async (input: string | URL, init?: RequestInit): Promise<Response> => {
|
|
975
|
+
sent.push({
|
|
976
|
+
challenge: new Headers(init?.headers).get(CHALLENGE_HEADER),
|
|
977
|
+
pathname: new URL(input.toString()).pathname,
|
|
978
|
+
});
|
|
979
|
+
return jsonResponse(
|
|
980
|
+
{challenge: "c"},
|
|
981
|
+
{headers: challengeHeader({[PASSKEY]: "pk.sig"})}
|
|
982
|
+
);
|
|
983
|
+
}) as never,
|
|
984
|
+
},
|
|
985
|
+
});
|
|
986
|
+
const client = createBetterAuthClient({
|
|
987
|
+
baseURL: "http://localhost:4000",
|
|
988
|
+
bearerStorage,
|
|
989
|
+
scheme: "terreno",
|
|
990
|
+
storagePrefix: "myapp",
|
|
991
|
+
webAuth: "bearer",
|
|
992
|
+
}) as unknown as {$fetch: (path: string, options: {method: string}) => Promise<unknown>};
|
|
993
|
+
|
|
994
|
+
await client.$fetch("/passkey/generate-authenticate-options", {method: "GET"});
|
|
995
|
+
|
|
996
|
+
expect(sent[0].challenge).toBe("-");
|
|
997
|
+
expect(bearerStorage.values.get("myapp_auth_challenge")).toBe(`${PASSKEY}=pk.sig`);
|
|
998
|
+
expect(bearerStorage.values.has(CHALLENGE_KEY)).toBe(false);
|
|
999
|
+
});
|
|
1000
|
+
});
|
|
1001
|
+
|
|
1002
|
+
interface HandoffRequest {
|
|
1003
|
+
authorization: string | null;
|
|
1004
|
+
body: unknown;
|
|
1005
|
+
// The page URL when the request left, to prove the token was already stripped from it.
|
|
1006
|
+
hrefAtRequest: string;
|
|
1007
|
+
pathname: string;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
interface FakeBrowser {
|
|
1011
|
+
assigned: string[];
|
|
1012
|
+
href: () => string;
|
|
1013
|
+
localStorage: MemoryStorage;
|
|
1014
|
+
replaced: string[];
|
|
1015
|
+
sessionStorage: MemoryStorage;
|
|
1016
|
+
setHref: (href: string) => void;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const NONCE_KEY = "terreno_oauth_handoff_nonce";
|
|
1020
|
+
|
|
1021
|
+
const installBrowser = (
|
|
1022
|
+
href: string,
|
|
1023
|
+
{
|
|
1024
|
+
replaceState,
|
|
1025
|
+
sessionStorage = createMemoryStorage(),
|
|
1026
|
+
}: {replaceState?: () => void; sessionStorage?: MemoryStorage} = {}
|
|
1027
|
+
): FakeBrowser => {
|
|
1028
|
+
let current = new URL(href);
|
|
1029
|
+
const assigned: string[] = [];
|
|
1030
|
+
const replaced: string[] = [];
|
|
1031
|
+
const localStorage = createMemoryStorage();
|
|
1032
|
+
(globalThis as {window?: unknown}).window = {
|
|
1033
|
+
history: {
|
|
1034
|
+
replaceState:
|
|
1035
|
+
replaceState ??
|
|
1036
|
+
((_state: unknown, _title: string, url: string): void => {
|
|
1037
|
+
current = new URL(url, current);
|
|
1038
|
+
replaced.push(current.href);
|
|
1039
|
+
}),
|
|
1040
|
+
state: null,
|
|
1041
|
+
},
|
|
1042
|
+
localStorage,
|
|
1043
|
+
location: {
|
|
1044
|
+
assign: (url: string): void => {
|
|
1045
|
+
assigned.push(url);
|
|
1046
|
+
},
|
|
1047
|
+
get href(): string {
|
|
1048
|
+
return current.href;
|
|
1049
|
+
},
|
|
1050
|
+
},
|
|
1051
|
+
sessionStorage,
|
|
1052
|
+
};
|
|
1053
|
+
return {
|
|
1054
|
+
assigned,
|
|
1055
|
+
href: (): string => current.href,
|
|
1056
|
+
localStorage,
|
|
1057
|
+
replaced,
|
|
1058
|
+
sessionStorage,
|
|
1059
|
+
setHref: (next: string): void => {
|
|
1060
|
+
current = new URL(next);
|
|
1061
|
+
},
|
|
1062
|
+
};
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// Makes createBetterAuthClient return the real Better Auth client, built from the options it
|
|
1066
|
+
// passed, with fetch replaced by a fake server.
|
|
1067
|
+
const useRealClient = (
|
|
1068
|
+
server: (pathname: string) => Response | Promise<Response>
|
|
1069
|
+
): {sent: HandoffRequest[]} => {
|
|
1070
|
+
const sent: HandoffRequest[] = [];
|
|
1071
|
+
captured.build = (config: Record<string, unknown>): unknown => {
|
|
1072
|
+
const customFetchImpl = async (
|
|
1073
|
+
input: string | URL | Request,
|
|
1074
|
+
init?: RequestInit
|
|
1075
|
+
): Promise<Response> => {
|
|
1076
|
+
const {pathname} = new URL(input instanceof Request ? input.url : input.toString());
|
|
1077
|
+
sent.push({
|
|
1078
|
+
authorization: new Headers(init?.headers).get("authorization"),
|
|
1079
|
+
body: typeof init?.body === "string" ? JSON.parse(init.body) : null,
|
|
1080
|
+
hrefAtRequest: (globalThis as {window: {location: {href: string}}}).window.location.href,
|
|
1081
|
+
pathname,
|
|
1082
|
+
});
|
|
1083
|
+
return server(pathname);
|
|
1084
|
+
};
|
|
1085
|
+
return createRealAuthClient({
|
|
1086
|
+
baseURL: config.baseURL as string,
|
|
1087
|
+
fetchOptions: {
|
|
1088
|
+
...(config.fetchOptions as Record<string, unknown>),
|
|
1089
|
+
customFetchImpl: customFetchImpl as never,
|
|
1090
|
+
},
|
|
1091
|
+
});
|
|
1092
|
+
};
|
|
1093
|
+
return {sent};
|
|
1094
|
+
};
|
|
1095
|
+
|
|
1096
|
+
const verifiedSession = (token: string): Response =>
|
|
1097
|
+
jsonResponse(
|
|
1098
|
+
{session: {id: "s1", token}, user: {id: "u1"}},
|
|
1099
|
+
{headers: {"set-auth-token": token}}
|
|
1100
|
+
);
|
|
1101
|
+
|
|
1102
|
+
describe("OAuth handoff for web bearer clients", () => {
|
|
1103
|
+
const globalWithWindow = globalThis as {window?: unknown};
|
|
1104
|
+
const hadWindow = "window" in globalWithWindow;
|
|
1105
|
+
const originalWindow = globalWithWindow.window;
|
|
1106
|
+
|
|
1107
|
+
beforeEach(() => {
|
|
1108
|
+
captured.auth = null;
|
|
1109
|
+
captured.build = null;
|
|
1110
|
+
});
|
|
1111
|
+
|
|
1112
|
+
afterEach(() => {
|
|
1113
|
+
captured.build = null;
|
|
1114
|
+
if (hadWindow) {
|
|
1115
|
+
globalWithWindow.window = originalWindow;
|
|
1116
|
+
} else {
|
|
1117
|
+
delete globalWithWindow.window;
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
|
|
1121
|
+
const createBearerClient = (bearerStorage: MemoryStorage = createMemoryStorage()) =>
|
|
1122
|
+
createBetterAuthClient({
|
|
1123
|
+
baseURL: "http://localhost:4000",
|
|
1124
|
+
bearerStorage,
|
|
1125
|
+
scheme: "terreno",
|
|
1126
|
+
webAuth: "bearer",
|
|
1127
|
+
});
|
|
1128
|
+
|
|
1129
|
+
// Starts a sign-in on the app's home page and returns the nonce it stored.
|
|
1130
|
+
const startSignIn = (client: BetterAuthClient, browser: FakeBrowser): string => {
|
|
1131
|
+
signInSocialWithHandoff({client, provider: "google"});
|
|
1132
|
+
const nonce = browser.sessionStorage.getItem(NONCE_KEY);
|
|
1133
|
+
if (!nonce) {
|
|
1134
|
+
throw new Error("no nonce stored");
|
|
1135
|
+
}
|
|
1136
|
+
return nonce;
|
|
1137
|
+
};
|
|
1138
|
+
|
|
1139
|
+
it("navigates to the start endpoint with a callbackURL carrying a fresh nonce", () => {
|
|
1140
|
+
const browser = installBrowser("http://localhost:8082/login");
|
|
1141
|
+
const client = createBearerClient();
|
|
1142
|
+
|
|
1143
|
+
signInSocialWithHandoff({
|
|
1144
|
+
callbackURL: "/auth/return?next=%2Ftodos",
|
|
1145
|
+
client,
|
|
1146
|
+
errorCallbackURL: "http://localhost:8082/login",
|
|
1147
|
+
provider: "google",
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
const nonce = browser.sessionStorage.getItem(NONCE_KEY) ?? "";
|
|
1151
|
+
expect(nonce).toMatch(/^[0-9a-f]{64}$/);
|
|
1152
|
+
expect(browser.assigned).toHaveLength(1);
|
|
1153
|
+
const start = new URL(browser.assigned[0]);
|
|
1154
|
+
expect(`${start.origin}${start.pathname}`).toBe(
|
|
1155
|
+
"http://localhost:4000/api/auth/oauth-handoff/start"
|
|
1156
|
+
);
|
|
1157
|
+
expect(start.searchParams.get("provider")).toBe("google");
|
|
1158
|
+
expect(start.searchParams.get("callbackURL")).toBe(
|
|
1159
|
+
`http://localhost:8082/auth/return?next=%2Ftodos&handoff=${nonce}`
|
|
1160
|
+
);
|
|
1161
|
+
expect(start.searchParams.get("errorCallbackURL")).toBe(
|
|
1162
|
+
`http://localhost:8082/login?handoff=${nonce}`
|
|
1163
|
+
);
|
|
1164
|
+
// The callbackURL travels encoded, so its own query cannot leak into the start URL's.
|
|
1165
|
+
expect(browser.assigned[0]).toContain(
|
|
1166
|
+
encodeURIComponent(`http://localhost:8082/auth/return?next=%2Ftodos&handoff=${nonce}`)
|
|
1167
|
+
);
|
|
1168
|
+
|
|
1169
|
+
signInSocialWithHandoff({client, provider: "google"});
|
|
1170
|
+
const second = browser.sessionStorage.getItem(NONCE_KEY);
|
|
1171
|
+
expect(second).not.toBe(nonce);
|
|
1172
|
+
const secondStart = new URL(browser.assigned[1]);
|
|
1173
|
+
expect(secondStart.searchParams.get("callbackURL")).toBe(
|
|
1174
|
+
`http://localhost:8082/?handoff=${second}`
|
|
1175
|
+
);
|
|
1176
|
+
// Without one, Better Auth would send callback errors to its own page on the API.
|
|
1177
|
+
expect(secondStart.searchParams.get("errorCallbackURL")).toBe(
|
|
1178
|
+
`http://localhost:8082/?handoff=${second}`
|
|
1179
|
+
);
|
|
1180
|
+
|
|
1181
|
+
// The app's own query reaches the return page as written, and a stale handoff is replaced.
|
|
1182
|
+
signInSocialWithHandoff({
|
|
1183
|
+
callbackURL: "/?q=a%20b&handoff=old#tab",
|
|
1184
|
+
client,
|
|
1185
|
+
provider: "google",
|
|
1186
|
+
});
|
|
1187
|
+
const third = browser.sessionStorage.getItem(NONCE_KEY);
|
|
1188
|
+
expect(new URL(browser.assigned[2]).searchParams.get("callbackURL")).toBe(
|
|
1189
|
+
`http://localhost:8082/?q=a%20b&handoff=${third}#tab`
|
|
1190
|
+
);
|
|
1191
|
+
});
|
|
1192
|
+
|
|
1193
|
+
it("uses a baseURL that already names the auth path, and a custom storagePrefix", () => {
|
|
1194
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1195
|
+
const client = createBetterAuthClient({
|
|
1196
|
+
baseURL: "https://api.example.net/custom/auth/",
|
|
1197
|
+
scheme: "terreno",
|
|
1198
|
+
storagePrefix: "myapp",
|
|
1199
|
+
webAuth: "bearer",
|
|
1200
|
+
});
|
|
1201
|
+
|
|
1202
|
+
signInSocialWithHandoff({client, provider: "github"});
|
|
1203
|
+
|
|
1204
|
+
expect(browser.assigned[0]).toStartWith(
|
|
1205
|
+
"https://api.example.net/custom/auth/oauth-handoff/start?"
|
|
1206
|
+
);
|
|
1207
|
+
expect(browser.sessionStorage.getItem("myapp_oauth_handoff_nonce")).toMatch(/^[0-9a-f]{64}$/);
|
|
1208
|
+
});
|
|
1209
|
+
|
|
1210
|
+
it("refuses to start outside web bearer mode, without a window, or without storage", () => {
|
|
1211
|
+
const cookieClient = createBetterAuthClient({baseURL: "http://localhost:4000", scheme: "t"});
|
|
1212
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1213
|
+
expect(() => signInSocialWithHandoff({client: cookieClient, provider: "google"})).toThrow(
|
|
1214
|
+
'webAuth: "bearer"'
|
|
1215
|
+
);
|
|
1216
|
+
expect(browser.assigned).toEqual([]);
|
|
1217
|
+
|
|
1218
|
+
const client = createBearerClient();
|
|
1219
|
+
delete globalWithWindow.window;
|
|
1220
|
+
expect(() => signInSocialWithHandoff({client, provider: "google"})).toThrow(
|
|
1221
|
+
'webAuth: "bearer"'
|
|
1222
|
+
);
|
|
1223
|
+
|
|
1224
|
+
const blocked = installBrowser("http://localhost:8082/", {
|
|
1225
|
+
sessionStorage: {
|
|
1226
|
+
...createMemoryStorage(),
|
|
1227
|
+
setItem: (): void => {
|
|
1228
|
+
throw new Error("QuotaExceededError");
|
|
1229
|
+
},
|
|
1230
|
+
},
|
|
1231
|
+
});
|
|
1232
|
+
expect(() => signInSocialWithHandoff({client, provider: "google"})).toThrow(
|
|
1233
|
+
"QuotaExceededError"
|
|
1234
|
+
);
|
|
1235
|
+
expect(blocked.assigned).toEqual([]);
|
|
1236
|
+
});
|
|
1237
|
+
|
|
1238
|
+
it("strips the token, then verifies it once and stores the bearer it returns", async () => {
|
|
1239
|
+
const bearerStorage = createMemoryStorage();
|
|
1240
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1241
|
+
const browser = installBrowser("http://localhost:8082/login");
|
|
1242
|
+
const client = createBearerClient(bearerStorage);
|
|
1243
|
+
const nonce = startSignIn(client, browser);
|
|
1244
|
+
browser.setHref(`http://localhost:8082/?next=%2Ftodos&handoff=${nonce}#ott=abc&tab=1`);
|
|
1245
|
+
|
|
1246
|
+
const stored = await completeBetterAuthOAuthHandoff({client});
|
|
1247
|
+
|
|
1248
|
+
expect(stored).toBe(true);
|
|
1249
|
+
expect(sent).toHaveLength(1);
|
|
1250
|
+
expect(sent[0].pathname).toBe("/api/auth/one-time-token/verify");
|
|
1251
|
+
expect(sent[0].body).toEqual({token: "abc"});
|
|
1252
|
+
// Other query and fragment parts survive; ott and handoff are gone before the request.
|
|
1253
|
+
expect(sent[0].hrefAtRequest).toBe("http://localhost:8082/?next=%2Ftodos#tab=1");
|
|
1254
|
+
expect(browser.href()).toBe("http://localhost:8082/?next=%2Ftodos#tab=1");
|
|
1255
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t2");
|
|
1256
|
+
expect(browser.sessionStorage.values.has(NONCE_KEY)).toBe(false);
|
|
1257
|
+
});
|
|
1258
|
+
|
|
1259
|
+
it("removes the query and fragment entirely when nothing else is in them", async () => {
|
|
1260
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1261
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1262
|
+
const client = createBearerClient();
|
|
1263
|
+
const nonce = startSignIn(client, browser);
|
|
1264
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1265
|
+
|
|
1266
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(true);
|
|
1267
|
+
|
|
1268
|
+
expect(sent[0].hrefAtRequest).toBe("http://localhost:8082/");
|
|
1269
|
+
});
|
|
1270
|
+
|
|
1271
|
+
it("ignores an unsolicited token: no stored nonce or a different one", async () => {
|
|
1272
|
+
const bearerStorage = createMemoryStorage();
|
|
1273
|
+
const {sent} = useRealClient(() => verifiedSession("attacker"));
|
|
1274
|
+
const browser = installBrowser("http://localhost:8082/?handoff=planted#ott=evil");
|
|
1275
|
+
const client = createBearerClient(bearerStorage);
|
|
1276
|
+
|
|
1277
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1278
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1279
|
+
|
|
1280
|
+
browser.sessionStorage.setItem(NONCE_KEY, "a".repeat(64));
|
|
1281
|
+
browser.setHref(`http://localhost:8082/?handoff=${"b".repeat(64)}#ott=evil`);
|
|
1282
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1283
|
+
|
|
1284
|
+
browser.setHref("http://localhost:8082/#ott=evil");
|
|
1285
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1286
|
+
|
|
1287
|
+
expect(sent).toEqual([]);
|
|
1288
|
+
expect(bearerStorage.values.size).toBe(0);
|
|
1289
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1290
|
+
// A mismatched return still uses up the nonce.
|
|
1291
|
+
expect(browser.sessionStorage.values.has(NONCE_KEY)).toBe(false);
|
|
1292
|
+
});
|
|
1293
|
+
|
|
1294
|
+
it("never sends a token from the query, and strips it from the URL", async () => {
|
|
1295
|
+
const bearerStorage = createMemoryStorage();
|
|
1296
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1297
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1298
|
+
const client = createBearerClient(bearerStorage);
|
|
1299
|
+
const nonce = startSignIn(client, browser);
|
|
1300
|
+
// The server only ever puts the token in the fragment; a query `ott` was planted.
|
|
1301
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}&ott=abc&next=%2Ftodos`);
|
|
1302
|
+
|
|
1303
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1304
|
+
|
|
1305
|
+
expect(sent).toEqual([]);
|
|
1306
|
+
expect(bearerStorage.values.size).toBe(0);
|
|
1307
|
+
expect(browser.href()).toBe("http://localhost:8082/?next=%2Ftodos");
|
|
1308
|
+
|
|
1309
|
+
// A planted query token is stripped even when nothing else of the handoff is there.
|
|
1310
|
+
browser.setHref("http://localhost:8082/?ott=abc#tab");
|
|
1311
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1312
|
+
expect(browser.href()).toBe("http://localhost:8082/#tab");
|
|
1313
|
+
expect(sent).toEqual([]);
|
|
1314
|
+
});
|
|
1315
|
+
|
|
1316
|
+
it("refuses a return that carries more than one token or nonce", async () => {
|
|
1317
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1318
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1319
|
+
const client = createBearerClient();
|
|
1320
|
+
const nonce = startSignIn(client, browser);
|
|
1321
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc&ott=def`);
|
|
1322
|
+
|
|
1323
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1324
|
+
|
|
1325
|
+
const again = startSignIn(client, browser);
|
|
1326
|
+
browser.setHref(`http://localhost:8082/?handoff=${again}&handoff=${again}#ott=abc`);
|
|
1327
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1328
|
+
|
|
1329
|
+
expect(sent).toEqual([]);
|
|
1330
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1331
|
+
});
|
|
1332
|
+
|
|
1333
|
+
it("makes no request and changes nothing on a page load without a handoff", async () => {
|
|
1334
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1335
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1336
|
+
const client = createBearerClient();
|
|
1337
|
+
const nonce = startSignIn(client, browser);
|
|
1338
|
+
browser.setHref("http://localhost:8082/todos?next=%2Fprofile#section");
|
|
1339
|
+
|
|
1340
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1341
|
+
|
|
1342
|
+
expect(sent).toEqual([]);
|
|
1343
|
+
expect(browser.replaced).toEqual([]);
|
|
1344
|
+
expect(browser.sessionStorage.getItem(NONCE_KEY)).toBe(nonce);
|
|
1345
|
+
});
|
|
1346
|
+
|
|
1347
|
+
it("leaves a provider error for the app and uses up the nonce", async () => {
|
|
1348
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1349
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1350
|
+
const client = createBearerClient();
|
|
1351
|
+
const nonce = startSignIn(client, browser);
|
|
1352
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}&error=sign_in_failed`);
|
|
1353
|
+
|
|
1354
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1355
|
+
|
|
1356
|
+
expect(sent).toEqual([]);
|
|
1357
|
+
expect(browser.href()).toBe("http://localhost:8082/?error=sign_in_failed");
|
|
1358
|
+
expect(browser.sessionStorage.values.has(NONCE_KEY)).toBe(false);
|
|
1359
|
+
});
|
|
1360
|
+
|
|
1361
|
+
it("strips the token but makes no request in cookie mode", async () => {
|
|
1362
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1363
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1364
|
+
const client = createBetterAuthClient({baseURL: "http://localhost:4000", scheme: "terreno"});
|
|
1365
|
+
browser.sessionStorage.setItem(NONCE_KEY, "a".repeat(64));
|
|
1366
|
+
browser.setHref(`http://localhost:8082/?handoff=${"a".repeat(64)}#ott=abc`);
|
|
1367
|
+
|
|
1368
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1369
|
+
|
|
1370
|
+
expect(sent).toEqual([]);
|
|
1371
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1372
|
+
});
|
|
1373
|
+
|
|
1374
|
+
it("resolves false with the URL stripped when verify fails or throws", async () => {
|
|
1375
|
+
const bearerStorage = createMemoryStorage();
|
|
1376
|
+
const responses: Array<() => Response> = [
|
|
1377
|
+
(): Response => jsonResponse({message: "Invalid token"}, {status: 400}),
|
|
1378
|
+
(): Response => {
|
|
1379
|
+
throw new TypeError("Failed to fetch");
|
|
1380
|
+
},
|
|
1381
|
+
// A 2xx without a token stores nothing either.
|
|
1382
|
+
(): Response => jsonResponse({session: {id: "s1"}, user: {id: "u1"}}),
|
|
1383
|
+
];
|
|
1384
|
+
const {sent} = useRealClient(() => {
|
|
1385
|
+
const next = responses.shift();
|
|
1386
|
+
if (!next) {
|
|
1387
|
+
throw new Error("unexpected request");
|
|
1388
|
+
}
|
|
1389
|
+
return next();
|
|
1390
|
+
});
|
|
1391
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1392
|
+
const client = createBearerClient(bearerStorage);
|
|
1393
|
+
|
|
1394
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1395
|
+
const nonce = startSignIn(client, browser);
|
|
1396
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1397
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1398
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
expect(sent).toHaveLength(3);
|
|
1402
|
+
expect(bearerStorage.values.size).toBe(0);
|
|
1403
|
+
});
|
|
1404
|
+
|
|
1405
|
+
it("keeps the verified token when a signed-out getSession sent before it lands after it", async () => {
|
|
1406
|
+
const bearerStorage = createMemoryStorage();
|
|
1407
|
+
let releaseSession: (response: Response) => void = () => {};
|
|
1408
|
+
let releaseVerify: (response: Response) => void = () => {};
|
|
1409
|
+
const {sent} = useRealClient((pathname) => {
|
|
1410
|
+
return new Promise<Response>((resolve) => {
|
|
1411
|
+
if (pathname.endsWith("/get-session")) {
|
|
1412
|
+
releaseSession = resolve;
|
|
1413
|
+
} else {
|
|
1414
|
+
releaseVerify = resolve;
|
|
1415
|
+
}
|
|
1416
|
+
});
|
|
1417
|
+
});
|
|
1418
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1419
|
+
const client = createBearerClient(bearerStorage);
|
|
1420
|
+
const nonce = startSignIn(client, browser);
|
|
1421
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1422
|
+
|
|
1423
|
+
const pendingSession = client.getSession();
|
|
1424
|
+
const pendingHandoff = completeBetterAuthOAuthHandoff({client});
|
|
1425
|
+
await Bun.sleep(0);
|
|
1426
|
+
expect(sent.map((request) => request.pathname)).toEqual([
|
|
1427
|
+
"/api/auth/get-session",
|
|
1428
|
+
"/api/auth/one-time-token/verify",
|
|
1429
|
+
]);
|
|
1430
|
+
releaseVerify(verifiedSession("t2"));
|
|
1431
|
+
await expect(pendingHandoff).resolves.toBe(true);
|
|
1432
|
+
releaseSession(jsonResponse(null));
|
|
1433
|
+
await pendingSession;
|
|
1434
|
+
|
|
1435
|
+
expect(sent[0].authorization).toBeNull();
|
|
1436
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t2");
|
|
1437
|
+
});
|
|
1438
|
+
|
|
1439
|
+
it("resolves false when a sign-out during verify drops the token", async () => {
|
|
1440
|
+
const bearerStorage = createMemoryStorage();
|
|
1441
|
+
let releaseVerify: (response: Response) => void = () => {};
|
|
1442
|
+
useRealClient((pathname) => {
|
|
1443
|
+
if (pathname.endsWith("/sign-out")) {
|
|
1444
|
+
return jsonResponse({success: true});
|
|
1445
|
+
}
|
|
1446
|
+
return new Promise<Response>((resolve) => {
|
|
1447
|
+
releaseVerify = resolve;
|
|
1448
|
+
});
|
|
1449
|
+
});
|
|
1450
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1451
|
+
const client = createBearerClient(bearerStorage);
|
|
1452
|
+
const nonce = startSignIn(client, browser);
|
|
1453
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1454
|
+
|
|
1455
|
+
const pendingHandoff = completeBetterAuthOAuthHandoff({client});
|
|
1456
|
+
await Bun.sleep(0);
|
|
1457
|
+
await client.signOut();
|
|
1458
|
+
releaseVerify(verifiedSession("t2"));
|
|
1459
|
+
|
|
1460
|
+
await expect(pendingHandoff).resolves.toBe(false);
|
|
1461
|
+
expect(bearerStorage.values.size).toBe(0);
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
it("resolves false, not a rejection, when the stored token cannot be read back", async () => {
|
|
1465
|
+
let reads = 0;
|
|
1466
|
+
const bearerStorage = {
|
|
1467
|
+
...createMemoryStorage(),
|
|
1468
|
+
getItem: (): string | null => {
|
|
1469
|
+
reads += 1;
|
|
1470
|
+
// The first read is the request's own auth header; the read-back after verify throws.
|
|
1471
|
+
if (reads > 1) {
|
|
1472
|
+
throw new Error("SecurityError");
|
|
1473
|
+
}
|
|
1474
|
+
return null;
|
|
1475
|
+
},
|
|
1476
|
+
};
|
|
1477
|
+
useRealClient(() => verifiedSession("t2"));
|
|
1478
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1479
|
+
const client = createBearerClient(bearerStorage);
|
|
1480
|
+
const nonce = startSignIn(client, browser);
|
|
1481
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1482
|
+
|
|
1483
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1484
|
+
});
|
|
1485
|
+
|
|
1486
|
+
it("tells mounted session hooks to refetch after a stored token", async () => {
|
|
1487
|
+
useRealClient(() => verifiedSession("t2"));
|
|
1488
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1489
|
+
const client = createBearerClient();
|
|
1490
|
+
const signal = client.$store.atoms.$sessionSignal;
|
|
1491
|
+
const before = signal.get();
|
|
1492
|
+
const nonce = startSignIn(client, browser);
|
|
1493
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1494
|
+
|
|
1495
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(true);
|
|
1496
|
+
expect(signal.get()).toBe(!before);
|
|
1497
|
+
});
|
|
1498
|
+
|
|
1499
|
+
it("verifies once when called twice, as React strict mode does", async () => {
|
|
1500
|
+
const bearerStorage = createMemoryStorage();
|
|
1501
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1502
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1503
|
+
const client = createBearerClient(bearerStorage);
|
|
1504
|
+
const nonce = startSignIn(client, browser);
|
|
1505
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1506
|
+
|
|
1507
|
+
const results = await Promise.all([
|
|
1508
|
+
completeBetterAuthOAuthHandoff({client}),
|
|
1509
|
+
completeBetterAuthOAuthHandoff({client}),
|
|
1510
|
+
]);
|
|
1511
|
+
|
|
1512
|
+
expect(results).toEqual([true, true]);
|
|
1513
|
+
expect(sent).toHaveLength(1);
|
|
1514
|
+
// A later call starts fresh and finds nothing to do.
|
|
1515
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1516
|
+
expect(sent).toHaveLength(1);
|
|
1517
|
+
});
|
|
1518
|
+
|
|
1519
|
+
it("makes no request when the URL cannot be stripped", async () => {
|
|
1520
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1521
|
+
const browser = installBrowser("http://localhost:8082/", {
|
|
1522
|
+
replaceState: (): void => {
|
|
1523
|
+
throw new Error("SecurityError");
|
|
1524
|
+
},
|
|
1525
|
+
});
|
|
1526
|
+
const client = createBearerClient();
|
|
1527
|
+
const nonce = startSignIn(client, browser);
|
|
1528
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce}#ott=abc`);
|
|
1529
|
+
|
|
1530
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1531
|
+
expect(sent).toEqual([]);
|
|
1532
|
+
});
|
|
1533
|
+
|
|
1534
|
+
it("treats unreadable session storage as a missing nonce", async () => {
|
|
1535
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1536
|
+
const browser = installBrowser("http://localhost:8082/?handoff=n#ott=abc", {
|
|
1537
|
+
sessionStorage: {
|
|
1538
|
+
...createMemoryStorage(),
|
|
1539
|
+
getItem: (): never => {
|
|
1540
|
+
throw new Error("SecurityError");
|
|
1541
|
+
},
|
|
1542
|
+
},
|
|
1543
|
+
});
|
|
1544
|
+
const client = createBearerClient();
|
|
1545
|
+
|
|
1546
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1547
|
+
expect(sent).toEqual([]);
|
|
1548
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1549
|
+
});
|
|
1550
|
+
|
|
1551
|
+
it("ignores a nonce of another length, a malformed part, and a missing location", async () => {
|
|
1552
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1553
|
+
const browser = installBrowser("http://localhost:8082/");
|
|
1554
|
+
const client = createBearerClient();
|
|
1555
|
+
const nonce = startSignIn(client, browser);
|
|
1556
|
+
browser.setHref(`http://localhost:8082/?handoff=${nonce.slice(1)}#ott=abc`);
|
|
1557
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1558
|
+
|
|
1559
|
+
const again = startSignIn(client, browser);
|
|
1560
|
+
browser.setHref(`http://localhost:8082/?handoff=${again}#ott=%E0%A4%A&x=%E0%A4%A`);
|
|
1561
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1562
|
+
// An undecodable part that is not the token is kept as it was.
|
|
1563
|
+
expect(browser.href()).toBe("http://localhost:8082/#x=%E0%A4%A");
|
|
1564
|
+
|
|
1565
|
+
globalWithWindow.window = {};
|
|
1566
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1567
|
+
expect(sent).toEqual([]);
|
|
1568
|
+
});
|
|
1569
|
+
|
|
1570
|
+
it("treats missing or blocked session storage as a missing nonce", async () => {
|
|
1571
|
+
const {sent} = useRealClient(() => verifiedSession("t2"));
|
|
1572
|
+
const client = createBearerClient();
|
|
1573
|
+
const browser = installBrowser("http://localhost:8082/?handoff=n#ott=abc");
|
|
1574
|
+
(globalWithWindow.window as {sessionStorage?: unknown}).sessionStorage = undefined;
|
|
1575
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1576
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1577
|
+
|
|
1578
|
+
browser.setHref("http://localhost:8082/?handoff=n#ott=abc");
|
|
1579
|
+
Object.defineProperty(globalWithWindow.window, "sessionStorage", {
|
|
1580
|
+
get: (): never => {
|
|
1581
|
+
throw new Error("SecurityError");
|
|
1582
|
+
},
|
|
1583
|
+
});
|
|
1584
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1585
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1586
|
+
expect(sent).toEqual([]);
|
|
1587
|
+
});
|
|
1588
|
+
|
|
1589
|
+
it("resolves false without a window or for a client it did not create", async () => {
|
|
1590
|
+
const client = createBearerClient();
|
|
1591
|
+
delete globalWithWindow.window;
|
|
1592
|
+
await expect(completeBetterAuthOAuthHandoff({client})).resolves.toBe(false);
|
|
1593
|
+
|
|
1594
|
+
const browser = installBrowser("http://localhost:8082/?handoff=n#ott=abc");
|
|
1595
|
+
const foreign = {} as BetterAuthClient;
|
|
1596
|
+
await expect(completeBetterAuthOAuthHandoff({client: foreign})).resolves.toBe(false);
|
|
1597
|
+
expect(browser.href()).toBe("http://localhost:8082/");
|
|
1598
|
+
});
|
|
1599
|
+
});
|
|
1600
|
+
|
|
1601
|
+
interface SubmittedForm {
|
|
1602
|
+
action: string;
|
|
1603
|
+
appended: boolean;
|
|
1604
|
+
fields: Record<string, string>;
|
|
1605
|
+
method: string;
|
|
1606
|
+
submitted: boolean;
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
// A document just big enough for the hidden form: it records the form and its fields.
|
|
1610
|
+
const installFormDocument = (): SubmittedForm[] => {
|
|
1611
|
+
const forms: SubmittedForm[] = [];
|
|
1612
|
+
const createElement = (tag: string): Record<string, unknown> => {
|
|
1613
|
+
if (tag === "form") {
|
|
1614
|
+
const form: SubmittedForm = {
|
|
1615
|
+
action: "",
|
|
1616
|
+
appended: false,
|
|
1617
|
+
fields: {},
|
|
1618
|
+
method: "",
|
|
1619
|
+
submitted: false,
|
|
1620
|
+
};
|
|
1621
|
+
forms.push(form);
|
|
1622
|
+
const element = {
|
|
1623
|
+
set action(value: string) {
|
|
1624
|
+
form.action = value;
|
|
1625
|
+
},
|
|
1626
|
+
appendChild: (child: {name: string; value: string}): void => {
|
|
1627
|
+
form.fields[child.name] = child.value;
|
|
1628
|
+
},
|
|
1629
|
+
set method(value: string) {
|
|
1630
|
+
form.method = value;
|
|
1631
|
+
},
|
|
1632
|
+
style: {} as Record<string, string>,
|
|
1633
|
+
submit: (): void => {
|
|
1634
|
+
form.submitted = true;
|
|
1635
|
+
},
|
|
1636
|
+
};
|
|
1637
|
+
formElements.set(element, form);
|
|
1638
|
+
return element;
|
|
1639
|
+
}
|
|
1640
|
+
return {name: "", style: {}, type: "", value: ""};
|
|
1641
|
+
};
|
|
1642
|
+
const formElements = new Map<object, SubmittedForm>();
|
|
1643
|
+
(globalThis as unknown as {window: Record<string, unknown>}).window.document = {
|
|
1644
|
+
body: {
|
|
1645
|
+
appendChild: (element: object): void => {
|
|
1646
|
+
const form = formElements.get(element);
|
|
1647
|
+
if (form) {
|
|
1648
|
+
form.appended = true;
|
|
1649
|
+
}
|
|
1650
|
+
},
|
|
1651
|
+
},
|
|
1652
|
+
createElement,
|
|
1653
|
+
};
|
|
1654
|
+
return forms;
|
|
1655
|
+
};
|
|
1656
|
+
|
|
1657
|
+
describe("linkSocialWithHandoff", () => {
|
|
1658
|
+
const globalWithWindow = globalThis as {window?: unknown};
|
|
1659
|
+
const hadWindow = "window" in globalWithWindow;
|
|
1660
|
+
const originalWindow = globalWithWindow.window;
|
|
1661
|
+
|
|
1662
|
+
beforeEach(() => {
|
|
1663
|
+
captured.auth = null;
|
|
1664
|
+
captured.build = null;
|
|
1665
|
+
});
|
|
1666
|
+
|
|
1667
|
+
afterEach(() => {
|
|
1668
|
+
captured.build = null;
|
|
1669
|
+
if (hadWindow) {
|
|
1670
|
+
globalWithWindow.window = originalWindow;
|
|
1671
|
+
} else {
|
|
1672
|
+
delete globalWithWindow.window;
|
|
1673
|
+
}
|
|
1674
|
+
});
|
|
1675
|
+
|
|
1676
|
+
const intentResponse = (): Response =>
|
|
1677
|
+
jsonResponse({
|
|
1678
|
+
startURL: "http://localhost:4000/api/auth/oauth-handoff/link-start",
|
|
1679
|
+
token: "link-token-1",
|
|
1680
|
+
});
|
|
1681
|
+
|
|
1682
|
+
it("posts the intent with the bearer, then submits the token in a hidden form", async () => {
|
|
1683
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "bearer-1"});
|
|
1684
|
+
const {sent} = useRealClient(() => intentResponse());
|
|
1685
|
+
const browser = installBrowser("http://localhost:8082/settings/security");
|
|
1686
|
+
const forms = installFormDocument();
|
|
1687
|
+
const client = createBetterAuthClient({
|
|
1688
|
+
baseURL: "http://localhost:4000",
|
|
1689
|
+
bearerStorage,
|
|
1690
|
+
scheme: "terreno",
|
|
1691
|
+
webAuth: "bearer",
|
|
1692
|
+
});
|
|
1693
|
+
|
|
1694
|
+
const result = await linkSocialWithHandoff({
|
|
1695
|
+
callbackURL: "/login?linked=google",
|
|
1696
|
+
client,
|
|
1697
|
+
provider: "google",
|
|
1698
|
+
});
|
|
1699
|
+
|
|
1700
|
+
expect(result).toEqual({error: null});
|
|
1701
|
+
expect(sent).toHaveLength(1);
|
|
1702
|
+
expect(sent[0].pathname).toBe("/api/auth/oauth-handoff/link-intent");
|
|
1703
|
+
expect(sent[0].authorization).toBe("Bearer bearer-1");
|
|
1704
|
+
// Absolute URLs, and the error page defaults to the return page.
|
|
1705
|
+
expect(sent[0].body).toEqual({
|
|
1706
|
+
callbackURL: "http://localhost:8082/login?linked=google",
|
|
1707
|
+
errorCallbackURL: "http://localhost:8082/login?linked=google",
|
|
1708
|
+
provider: "google",
|
|
1709
|
+
});
|
|
1710
|
+
expect(forms).toEqual([
|
|
1711
|
+
{
|
|
1712
|
+
action: "http://localhost:4000/api/auth/oauth-handoff/link-start",
|
|
1713
|
+
appended: true,
|
|
1714
|
+
fields: {token: "link-token-1"},
|
|
1715
|
+
method: "POST",
|
|
1716
|
+
submitted: true,
|
|
1717
|
+
},
|
|
1718
|
+
]);
|
|
1719
|
+
// The token never goes into the page URL.
|
|
1720
|
+
expect(browser.assigned).toEqual([]);
|
|
1721
|
+
expect(browser.href()).toBe("http://localhost:8082/settings/security");
|
|
1722
|
+
});
|
|
1723
|
+
|
|
1724
|
+
it("passes an errorCallbackURL through", async () => {
|
|
1725
|
+
const {sent} = useRealClient(() => intentResponse());
|
|
1726
|
+
installBrowser("http://localhost:8082/settings");
|
|
1727
|
+
installFormDocument();
|
|
1728
|
+
const client = createBetterAuthClient({
|
|
1729
|
+
baseURL: "http://localhost:4000",
|
|
1730
|
+
bearerStorage: createMemoryStorage({terreno_bearer_token: "bearer-1"}),
|
|
1731
|
+
scheme: "terreno",
|
|
1732
|
+
webAuth: "bearer",
|
|
1733
|
+
});
|
|
1734
|
+
|
|
1735
|
+
await linkSocialWithHandoff({
|
|
1736
|
+
callbackURL: "http://localhost:8082/login",
|
|
1737
|
+
client,
|
|
1738
|
+
errorCallbackURL: "/settings?tab=security",
|
|
1739
|
+
provider: "github",
|
|
1740
|
+
});
|
|
1741
|
+
|
|
1742
|
+
expect((sent[0].body as {errorCallbackURL: string}).errorCallbackURL).toBe(
|
|
1743
|
+
"http://localhost:8082/settings?tab=security"
|
|
1744
|
+
);
|
|
1745
|
+
});
|
|
1746
|
+
|
|
1747
|
+
it("returns the refusal and submits nothing when the intent is refused", async () => {
|
|
1748
|
+
useRealClient(() =>
|
|
1749
|
+
jsonResponse(
|
|
1750
|
+
{code: "LINKING_DISABLED", message: "Account linking is turned off"},
|
|
1751
|
+
{status: 403}
|
|
1752
|
+
)
|
|
1753
|
+
);
|
|
1754
|
+
installBrowser("http://localhost:8082/settings");
|
|
1755
|
+
const forms = installFormDocument();
|
|
1756
|
+
const client = createBetterAuthClient({
|
|
1757
|
+
baseURL: "http://localhost:4000",
|
|
1758
|
+
bearerStorage: createMemoryStorage({terreno_bearer_token: "bearer-1"}),
|
|
1759
|
+
scheme: "terreno",
|
|
1760
|
+
webAuth: "bearer",
|
|
1761
|
+
});
|
|
1762
|
+
|
|
1763
|
+
const result = await linkSocialWithHandoff({callbackURL: "/login", client, provider: "google"});
|
|
1764
|
+
|
|
1765
|
+
expect(result.error).toEqual({
|
|
1766
|
+
code: "LINKING_DISABLED",
|
|
1767
|
+
message: "Account linking is turned off",
|
|
1768
|
+
status: 403,
|
|
1769
|
+
});
|
|
1770
|
+
expect(forms).toEqual([]);
|
|
1771
|
+
});
|
|
1772
|
+
|
|
1773
|
+
it("refuses a start URL that is not http(s) and submits nothing", async () => {
|
|
1774
|
+
useRealClient(() => jsonResponse({startURL: "javascript:alert(1)", token: "t"}));
|
|
1775
|
+
installBrowser("http://localhost:8082/settings");
|
|
1776
|
+
const forms = installFormDocument();
|
|
1777
|
+
const client = createBetterAuthClient({
|
|
1778
|
+
baseURL: "http://localhost:4000",
|
|
1779
|
+
bearerStorage: createMemoryStorage({terreno_bearer_token: "bearer-1"}),
|
|
1780
|
+
scheme: "terreno",
|
|
1781
|
+
webAuth: "bearer",
|
|
1782
|
+
});
|
|
1783
|
+
|
|
1784
|
+
const result = await linkSocialWithHandoff({callbackURL: "/login", client, provider: "google"});
|
|
1785
|
+
|
|
1786
|
+
expect(result.error?.status).toBe(500);
|
|
1787
|
+
expect(forms).toEqual([]);
|
|
1788
|
+
});
|
|
1789
|
+
|
|
1790
|
+
it("calls linkSocial in cookie mode, with no intent and no form", async () => {
|
|
1791
|
+
const calls: unknown[] = [];
|
|
1792
|
+
captured.build = (): unknown => ({
|
|
1793
|
+
linkSocial: async (body: unknown): Promise<{data: unknown; error: null}> => {
|
|
1794
|
+
calls.push(body);
|
|
1795
|
+
return {data: {redirect: true, url: "https://accounts.google.com/o"}, error: null};
|
|
1796
|
+
},
|
|
1797
|
+
});
|
|
1798
|
+
installBrowser("http://localhost:8082/settings");
|
|
1799
|
+
const forms = installFormDocument();
|
|
1800
|
+
const client = createBetterAuthClient({baseURL: "http://localhost:4000", scheme: "terreno"});
|
|
1801
|
+
|
|
1802
|
+
const result = await linkSocialWithHandoff({
|
|
1803
|
+
callbackURL: "/settings",
|
|
1804
|
+
client,
|
|
1805
|
+
provider: "google",
|
|
1806
|
+
});
|
|
1807
|
+
|
|
1808
|
+
expect(result).toEqual({error: null});
|
|
1809
|
+
expect(calls).toEqual([{callbackURL: "/settings", provider: "google"}]);
|
|
1810
|
+
expect(forms).toEqual([]);
|
|
1811
|
+
});
|
|
1812
|
+
|
|
1813
|
+
it("returns linkSocial's error in cookie mode", async () => {
|
|
1814
|
+
const calls: unknown[] = [];
|
|
1815
|
+
captured.build = (): unknown => ({
|
|
1816
|
+
linkSocial: async (body: unknown): Promise<{data: null; error: Record<string, unknown>}> => {
|
|
1817
|
+
calls.push(body);
|
|
1818
|
+
return {
|
|
1819
|
+
data: null,
|
|
1820
|
+
error: {code: "LINKING_DISABLED", message: "off", status: 403, statusText: "Forbidden"},
|
|
1821
|
+
};
|
|
1822
|
+
},
|
|
1823
|
+
});
|
|
1824
|
+
installBrowser("http://localhost:8082/settings");
|
|
1825
|
+
const client = createBetterAuthClient({baseURL: "http://localhost:4000", scheme: "terreno"});
|
|
1826
|
+
|
|
1827
|
+
const result = await linkSocialWithHandoff({
|
|
1828
|
+
callbackURL: "/settings",
|
|
1829
|
+
client,
|
|
1830
|
+
errorCallbackURL: "/settings?failed=1",
|
|
1831
|
+
provider: "google",
|
|
1832
|
+
});
|
|
1833
|
+
|
|
1834
|
+
expect(result.error).toEqual({code: "LINKING_DISABLED", message: "off", status: 403});
|
|
1835
|
+
expect(calls).toEqual([
|
|
1836
|
+
{callbackURL: "/settings", errorCallbackURL: "/settings?failed=1", provider: "google"},
|
|
1837
|
+
]);
|
|
1838
|
+
});
|
|
1839
|
+
|
|
1840
|
+
it("calls linkSocial for a bearer-configured client when there is no window", async () => {
|
|
1841
|
+
const calls: unknown[] = [];
|
|
1842
|
+
const fetched: string[] = [];
|
|
1843
|
+
captured.build = (): unknown => ({
|
|
1844
|
+
$fetch: async (path: string): Promise<{data: null; error: null}> => {
|
|
1845
|
+
fetched.push(path);
|
|
1846
|
+
return {data: null, error: null};
|
|
1847
|
+
},
|
|
1848
|
+
linkSocial: async (body: unknown): Promise<{data: unknown; error: null}> => {
|
|
1849
|
+
calls.push(body);
|
|
1850
|
+
return {data: {redirect: false, url: ""}, error: null};
|
|
1851
|
+
},
|
|
1852
|
+
});
|
|
1853
|
+
const client = createBetterAuthClient({
|
|
1854
|
+
baseURL: "http://localhost:4000",
|
|
1855
|
+
bearerStorage: createMemoryStorage({terreno_bearer_token: "bearer-1"}),
|
|
1856
|
+
scheme: "terreno",
|
|
1857
|
+
webAuth: "bearer",
|
|
1858
|
+
});
|
|
1859
|
+
delete globalWithWindow.window;
|
|
1860
|
+
|
|
1861
|
+
const result = await linkSocialWithHandoff({
|
|
1862
|
+
callbackURL: "/settings",
|
|
1863
|
+
client,
|
|
1864
|
+
provider: "github",
|
|
1865
|
+
});
|
|
1866
|
+
|
|
1867
|
+
expect(result).toEqual({error: null});
|
|
1868
|
+
expect(calls).toEqual([{callbackURL: "/settings", provider: "github"}]);
|
|
1869
|
+
expect(fetched).toEqual([]);
|
|
1870
|
+
});
|
|
1871
|
+
});
|
|
1872
|
+
|
|
1873
|
+
interface FeatureRequest {
|
|
1874
|
+
method: string | undefined;
|
|
1875
|
+
pathname: string;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
// Loose view of the real client the feature tests drive, since the test file is not type-checked
|
|
1879
|
+
// against the feature overloads.
|
|
1880
|
+
interface FeatureClient {
|
|
1881
|
+
getLastUsedLoginMethod: () => string | null;
|
|
1882
|
+
isLastUsedLoginMethod: (method: string) => boolean;
|
|
1883
|
+
multiSession: {listDeviceSessions: () => Promise<unknown>};
|
|
1884
|
+
oneTimeToken: {verify: (body: {token: string}) => Promise<unknown>};
|
|
1885
|
+
passkey: {addPasskey: () => Promise<{error: unknown}>};
|
|
1886
|
+
signIn: {email: (body: {email: string; password: string}) => Promise<unknown>};
|
|
1887
|
+
twoFactor: {enable: (body: {password: string}) => Promise<unknown>};
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
// Makes createBetterAuthClient return the real Better Auth client built from the plugins and
|
|
1891
|
+
// options it passed, with fetch replaced by a fake server.
|
|
1892
|
+
const useRealFeatureClient = (
|
|
1893
|
+
server: FakeServer
|
|
1894
|
+
): {auth: Array<Omit<SentRequest, "pathname">>; sent: FeatureRequest[]} => {
|
|
1895
|
+
const sent: FeatureRequest[] = [];
|
|
1896
|
+
const auth: Array<Omit<SentRequest, "pathname">> = [];
|
|
1897
|
+
captured.build = (config: Record<string, unknown>): unknown => {
|
|
1898
|
+
const customFetchImpl = async (input: string | URL, init?: RequestInit): Promise<Response> => {
|
|
1899
|
+
sent.push({method: init?.method, pathname: new URL(input.toString()).pathname});
|
|
1900
|
+
auth.push({
|
|
1901
|
+
authorization: new Headers(init?.headers).get("authorization"),
|
|
1902
|
+
credentials: init?.credentials,
|
|
1903
|
+
});
|
|
1904
|
+
return server(new URL(input.toString()).pathname);
|
|
1905
|
+
};
|
|
1906
|
+
return createRealAuthClient({
|
|
1907
|
+
baseURL: config.baseURL as string,
|
|
1908
|
+
fetchOptions: {
|
|
1909
|
+
...(config.fetchOptions as Record<string, unknown>),
|
|
1910
|
+
customFetchImpl: customFetchImpl as never,
|
|
1911
|
+
},
|
|
1912
|
+
// The mocked expo plugin has no hooks, so the real client runs only the feature plugins.
|
|
1913
|
+
plugins: config.plugins as never,
|
|
1914
|
+
});
|
|
1915
|
+
};
|
|
1916
|
+
return {auth, sent};
|
|
1917
|
+
};
|
|
1918
|
+
|
|
1919
|
+
const pluginIds = (): unknown[] => {
|
|
1920
|
+
const plugins = (captured.auth?.plugins ?? []) as Array<{id?: string; name?: string}>;
|
|
1921
|
+
return plugins.map((plugin) => plugin.id ?? plugin.name);
|
|
1922
|
+
};
|
|
1923
|
+
|
|
1924
|
+
const createFeatureClient = (features: BetterAuthClientFeatures): FeatureClient => {
|
|
1925
|
+
return createBetterAuthClient({
|
|
1926
|
+
baseURL: "http://localhost:4000",
|
|
1927
|
+
features,
|
|
1928
|
+
scheme: "terreno",
|
|
1929
|
+
}) as unknown as FeatureClient;
|
|
1930
|
+
};
|
|
1931
|
+
|
|
1932
|
+
describe("createBetterAuthClient features", () => {
|
|
1933
|
+
const globalWithDocument = globalThis as {document?: unknown};
|
|
1934
|
+
const hadDocument = "document" in globalWithDocument;
|
|
1935
|
+
const originalDocument = globalWithDocument.document;
|
|
1936
|
+
|
|
1937
|
+
beforeEach(() => {
|
|
1938
|
+
captured.auth = null;
|
|
1939
|
+
captured.build = null;
|
|
1940
|
+
});
|
|
1941
|
+
|
|
1942
|
+
afterEach(() => {
|
|
1943
|
+
captured.build = null;
|
|
1944
|
+
if (hadDocument) {
|
|
1945
|
+
globalWithDocument.document = originalDocument;
|
|
1946
|
+
} else {
|
|
1947
|
+
delete globalWithDocument.document;
|
|
1948
|
+
}
|
|
1949
|
+
});
|
|
1950
|
+
|
|
1951
|
+
it("registers only the expo plugin without features, as before", () => {
|
|
1952
|
+
createBetterAuthClient({baseURL: "http://localhost:4000", scheme: "terreno"});
|
|
1953
|
+
expect(pluginIds()).toEqual(["expo-plugin"]);
|
|
1954
|
+
expect(Object.keys(captured.auth ?? {}).sort()).toEqual(["baseURL", "plugins"]);
|
|
1955
|
+
});
|
|
1956
|
+
|
|
1957
|
+
it("registers no feature plugins for features that are off", () => {
|
|
1958
|
+
createFeatureClient({});
|
|
1959
|
+
expect(pluginIds()).toEqual(["expo-plugin"]);
|
|
1960
|
+
createFeatureClient({
|
|
1961
|
+
lastLoginMethod: false,
|
|
1962
|
+
multiSession: false,
|
|
1963
|
+
oneTimeToken: false,
|
|
1964
|
+
passkey: false,
|
|
1965
|
+
twoFactor: false,
|
|
1966
|
+
});
|
|
1967
|
+
expect(pluginIds()).toEqual(["expo-plugin"]);
|
|
1968
|
+
});
|
|
1969
|
+
|
|
1970
|
+
it("registers every feature plugin after the expo plugin", () => {
|
|
1971
|
+
createFeatureClient({
|
|
1972
|
+
lastLoginMethod: true,
|
|
1973
|
+
multiSession: true,
|
|
1974
|
+
oneTimeToken: true,
|
|
1975
|
+
passkey: true,
|
|
1976
|
+
twoFactor: true,
|
|
1977
|
+
});
|
|
1978
|
+
expect(pluginIds()).toEqual([
|
|
1979
|
+
"expo-plugin",
|
|
1980
|
+
"two-factor",
|
|
1981
|
+
"passkey",
|
|
1982
|
+
"multi-session",
|
|
1983
|
+
"last-login-method-client",
|
|
1984
|
+
"one-time-token",
|
|
1985
|
+
]);
|
|
1986
|
+
});
|
|
1987
|
+
|
|
1988
|
+
it("twoFactor exposes client.twoFactor, posting enable to /two-factor/enable", async () => {
|
|
1989
|
+
const {sent} = useRealFeatureClient(() => jsonResponse({totpURI: "otpauth://x"}));
|
|
1990
|
+
const client = createFeatureClient({twoFactor: true});
|
|
1991
|
+
|
|
1992
|
+
await client.twoFactor.enable({password: "secret"});
|
|
1993
|
+
|
|
1994
|
+
expect(pluginIds()).toContain("two-factor");
|
|
1995
|
+
expect(sent).toEqual([{method: "POST", pathname: "/api/auth/two-factor/enable"}]);
|
|
1996
|
+
});
|
|
1997
|
+
|
|
1998
|
+
it("twoFactor calls onTwoFactorRedirect with the methods when sign-in needs a second factor", async () => {
|
|
1999
|
+
useRealFeatureClient(() => jsonResponse({twoFactorMethods: ["totp"], twoFactorRedirect: true}));
|
|
2000
|
+
const redirects: unknown[] = [];
|
|
2001
|
+
const client = createFeatureClient({
|
|
2002
|
+
twoFactor: {
|
|
2003
|
+
onTwoFactorRedirect: (context): void => {
|
|
2004
|
+
redirects.push(context);
|
|
2005
|
+
},
|
|
2006
|
+
},
|
|
2007
|
+
});
|
|
2008
|
+
|
|
2009
|
+
await client.signIn.email({email: "a@example.com", password: "secret"});
|
|
2010
|
+
|
|
2011
|
+
expect(redirects).toEqual([{twoFactorMethods: ["totp"]}]);
|
|
2012
|
+
});
|
|
2013
|
+
|
|
2014
|
+
it("passkey exposes client.passkey.addPasskey, which asks /passkey/generate-register-options", async () => {
|
|
2015
|
+
const {sent} = useRealFeatureClient(() => jsonResponse({message: "nope"}, {status: 401}));
|
|
2016
|
+
const client = createFeatureClient({passkey: true});
|
|
2017
|
+
|
|
2018
|
+
const result = await client.passkey.addPasskey();
|
|
2019
|
+
|
|
2020
|
+
expect(result.error).toBeTruthy();
|
|
2021
|
+
expect(sent).toEqual([
|
|
2022
|
+
{method: "GET", pathname: "/api/auth/passkey/generate-register-options"},
|
|
2023
|
+
]);
|
|
2024
|
+
});
|
|
2025
|
+
|
|
2026
|
+
it("multiSession exposes client.multiSession, reading /multi-session/list-device-sessions", async () => {
|
|
2027
|
+
const {sent} = useRealFeatureClient(() => jsonResponse([]));
|
|
2028
|
+
const client = createFeatureClient({multiSession: true});
|
|
2029
|
+
|
|
2030
|
+
await client.multiSession.listDeviceSessions();
|
|
2031
|
+
|
|
2032
|
+
expect(pluginIds()).toContain("multi-session");
|
|
2033
|
+
expect(sent).toEqual([
|
|
2034
|
+
{method: "GET", pathname: "/api/auth/multi-session/list-device-sessions"},
|
|
2035
|
+
]);
|
|
2036
|
+
});
|
|
2037
|
+
|
|
2038
|
+
it("lastLoginMethod exposes getLastUsedLoginMethod, read from the cookie with no request", () => {
|
|
2039
|
+
const {sent} = useRealFeatureClient(() => jsonResponse({}));
|
|
2040
|
+
globalWithDocument.document = {cookie: "better-auth.last_used_login_method=github"};
|
|
2041
|
+
const client = createFeatureClient({lastLoginMethod: true});
|
|
2042
|
+
|
|
2043
|
+
expect(client.getLastUsedLoginMethod()).toBe("github");
|
|
2044
|
+
expect(client.isLastUsedLoginMethod("github")).toBe(true);
|
|
2045
|
+
expect(sent).toEqual([]);
|
|
2046
|
+
});
|
|
2047
|
+
|
|
2048
|
+
it("sends feature calls with the stored bearer and no cookies in web bearer mode", async () => {
|
|
2049
|
+
const bearerStorage = createMemoryStorage({terreno_bearer_token: "t1"});
|
|
2050
|
+
const {auth, sent} = useRealFeatureClient(() =>
|
|
2051
|
+
jsonResponse({totpURI: "otpauth://x"}, {headers: {"set-auth-token": "t2"}})
|
|
2052
|
+
);
|
|
2053
|
+
const client = createBetterAuthClient({
|
|
2054
|
+
baseURL: "http://localhost:4000",
|
|
2055
|
+
bearerStorage,
|
|
2056
|
+
features: {twoFactor: true},
|
|
2057
|
+
scheme: "terreno",
|
|
2058
|
+
webAuth: "bearer",
|
|
2059
|
+
}) as unknown as FeatureClient;
|
|
2060
|
+
|
|
2061
|
+
await client.twoFactor.enable({password: "secret"});
|
|
2062
|
+
|
|
2063
|
+
expect(sent).toEqual([{method: "POST", pathname: "/api/auth/two-factor/enable"}]);
|
|
2064
|
+
expect(auth).toEqual([{authorization: "Bearer t1", credentials: "omit"}]);
|
|
2065
|
+
// A token a feature endpoint issues replaces the stored one.
|
|
2066
|
+
expect(bearerStorage.values.get("terreno_bearer_token")).toBe("t2");
|
|
2067
|
+
});
|
|
2068
|
+
|
|
2069
|
+
it("oneTimeToken exposes client.oneTimeToken, posting verify to /one-time-token/verify", async () => {
|
|
2070
|
+
const {sent} = useRealFeatureClient(() => jsonResponse({session: null}));
|
|
2071
|
+
const client = createFeatureClient({oneTimeToken: true});
|
|
2072
|
+
|
|
2073
|
+
await client.oneTimeToken.verify({token: "t"});
|
|
2074
|
+
|
|
2075
|
+
expect(pluginIds()).toContain("one-time-token");
|
|
2076
|
+
expect(sent).toEqual([{method: "POST", pathname: "/api/auth/one-time-token/verify"}]);
|
|
2077
|
+
});
|
|
2078
|
+
});
|
|
2079
|
+
|
|
2080
|
+
describe("createBetterAuthClient options outside web bearer mode", () => {
|
|
2081
|
+
beforeEach(() => {
|
|
2082
|
+
captured.auth = null;
|
|
2083
|
+
});
|
|
2084
|
+
|
|
2085
|
+
it("passes only baseURL and plugins on web without webAuth or with cookie", () => {
|
|
2086
|
+
createBetterAuthClient({baseURL: "http://localhost:3000", scheme: "terreno"});
|
|
2087
|
+
expect(Object.keys(captured.auth ?? {}).sort()).toEqual(["baseURL", "plugins"]);
|
|
2088
|
+
createBetterAuthClient({
|
|
2089
|
+
baseURL: "http://localhost:3000",
|
|
2090
|
+
scheme: "terreno",
|
|
2091
|
+
webAuth: "cookie",
|
|
2092
|
+
});
|
|
2093
|
+
expect(Object.keys(captured.auth ?? {}).sort()).toEqual(["baseURL", "plugins"]);
|
|
2094
|
+
});
|
|
2095
|
+
});
|
|
2096
|
+
|
|
2097
|
+
describe("createBetterAuthClient", () => {
|
|
2098
|
+
beforeEach(() => {
|
|
2099
|
+
captured.auth = null;
|
|
2100
|
+
captured.expo = null;
|
|
2101
|
+
});
|
|
2102
|
+
|
|
2103
|
+
afterAll(() => {
|
|
2104
|
+
// Restore the test-preload mocks so later test files aren't polluted.
|
|
2105
|
+
mock.module("@better-auth/expo/client", () => ({
|
|
2106
|
+
expoClient: () => ({name: "expo-plugin"}),
|
|
2107
|
+
}));
|
|
2108
|
+
mock.module("better-auth/react", () => ({
|
|
2109
|
+
createAuthClient: () => ({}),
|
|
2110
|
+
}));
|
|
2111
|
+
mock.module("expo-secure-store", () => ({
|
|
2112
|
+
deleteItemAsync: async () => {},
|
|
2113
|
+
getItem: () => null,
|
|
2114
|
+
getItemAsync: async () => null,
|
|
2115
|
+
setItem: () => {},
|
|
2116
|
+
setItemAsync: async () => {},
|
|
2117
|
+
}));
|
|
2118
|
+
});
|
|
2119
|
+
|
|
2120
|
+
it("passes baseURL and scheme through to the Better Auth client", () => {
|
|
2121
|
+
const client = createBetterAuthClient({
|
|
2122
|
+
baseURL: "http://localhost:3000",
|
|
2123
|
+
scheme: "terreno",
|
|
2124
|
+
});
|
|
2125
|
+
expect(captured.auth).not.toBeNull();
|
|
2126
|
+
expect(captured.auth?.baseURL).toBe("http://localhost:3000");
|
|
2127
|
+
expect(captured.expo?.scheme).toBe("terreno");
|
|
2128
|
+
expect(captured.expo?.storagePrefix).toBe("terreno");
|
|
2129
|
+
expect(captured.expo?.storage).toBeDefined();
|
|
2130
|
+
expect(client).toBeDefined();
|
|
2131
|
+
});
|
|
2132
|
+
|
|
2133
|
+
it("returns a client typed for the session store and the syncdb auth adapter", () => {
|
|
2134
|
+
const client = createBetterAuthClient({baseURL: "http://localhost:3000", scheme: "terreno"});
|
|
2135
|
+
// Compile-time contract (checked by `bun run compile`): the full Better Auth client type
|
|
2136
|
+
// must survive the Expo plugin cast, or SessionProvider/betterAuthAdapter reject it.
|
|
2137
|
+
const sessionClient: BetterAuthSessionClientLike = client;
|
|
2138
|
+
const bridged = bridgeBetterAuthReactClient(client);
|
|
2139
|
+
expect(sessionClient).toBe(client);
|
|
2140
|
+
expect(typeof bridged.getSession).toBe("function");
|
|
2141
|
+
});
|
|
2142
|
+
|
|
2143
|
+
it("uses a custom storagePrefix when provided", () => {
|
|
2144
|
+
createBetterAuthClient({
|
|
2145
|
+
baseURL: "http://localhost:3000",
|
|
2146
|
+
scheme: "terreno",
|
|
2147
|
+
storagePrefix: "custom",
|
|
2148
|
+
});
|
|
2149
|
+
expect(captured.expo?.storagePrefix).toBe("custom");
|
|
2150
|
+
});
|
|
2151
|
+
|
|
2152
|
+
it("hands the plugin a storage that repairs the jar under the configured prefix", async () => {
|
|
2153
|
+
const globalWithWindow = globalThis as {window?: unknown; document?: unknown};
|
|
2154
|
+
const hadWindow = "window" in globalWithWindow;
|
|
2155
|
+
const hadDocument = "document" in globalWithWindow;
|
|
2156
|
+
const originalGet = AsyncStorage.getItem;
|
|
2157
|
+
// A `document` makes the default adapter take the web (AsyncStorage) branch.
|
|
2158
|
+
globalWithWindow.window = {};
|
|
2159
|
+
globalWithWindow.document = {};
|
|
2160
|
+
AsyncStorage.getItem = async (key: string): Promise<string | null> => {
|
|
2161
|
+
return key === "custom_cookie" ? CORRUPT_JAR : `async-${key}`;
|
|
2162
|
+
};
|
|
2163
|
+
|
|
2164
|
+
try {
|
|
2165
|
+
createBetterAuthClient({
|
|
2166
|
+
baseURL: "http://localhost:3000",
|
|
2167
|
+
scheme: "terreno",
|
|
2168
|
+
storagePrefix: "custom",
|
|
2169
|
+
});
|
|
2170
|
+
|
|
2171
|
+
const jar = await captured.expo?.storage?.getItem("custom_cookie");
|
|
2172
|
+
expect(() => readJarLikeExpoPlugin(jar as string)).not.toThrow();
|
|
2173
|
+
expect(await captured.expo?.storage?.getItem("custom_session_data")).toBe(
|
|
2174
|
+
"async-custom_session_data"
|
|
2175
|
+
);
|
|
2176
|
+
} finally {
|
|
2177
|
+
AsyncStorage.getItem = originalGet;
|
|
2178
|
+
if (!hadWindow) {
|
|
2179
|
+
delete globalWithWindow.window;
|
|
2180
|
+
}
|
|
2181
|
+
if (!hadDocument) {
|
|
2182
|
+
delete globalWithWindow.document;
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
});
|
|
2186
|
+
|
|
2187
|
+
it("defaults to the synchronous SecureStore adapter on native (no document)", () => {
|
|
2188
|
+
resetSecureCalls();
|
|
2189
|
+
mockSecureStore();
|
|
2190
|
+
createBetterAuthClient({baseURL: "http://localhost:3000", scheme: "terreno"});
|
|
2191
|
+
|
|
2192
|
+
const jar = captured.expo?.storage?.getItem("terreno_cookie");
|
|
2193
|
+
|
|
2194
|
+
expect(jar).not.toBeInstanceOf(Promise);
|
|
2195
|
+
expect(() => readJarLikeExpoPlugin(jar as string)).not.toThrow();
|
|
2196
|
+
expect(secureCalls.getSync).toEqual(["terreno_cookie"]);
|
|
2197
|
+
});
|
|
2198
|
+
});
|