@terreno/api 57.19.2 → 57.21.0
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 +443 -0
- package/biome.jsonc +1 -0
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.d.ts +3 -3
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/frameworkModelNames.d.ts +4 -0
- package/dist/frameworkModelNames.js +4 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.js +29 -3
- package/dist/mcp/adminTracking.d.ts +28 -0
- package/dist/mcp/adminTracking.js +80 -0
- package/dist/mcp/auth.d.ts +6 -0
- package/dist/mcp/auth.js +12 -2
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +48 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +55 -4
- package/dist/models/mcpRequestLog.d.ts +2 -0
- package/dist/models/mcpRequestLog.js +73 -0
- package/dist/models/mcpServiceToken.js +4 -0
- package/dist/models/mcpToolSetting.d.ts +2 -0
- package/dist/models/mcpToolSetting.js +119 -0
- package/dist/models/versionConfig.d.ts +2 -0
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/auditModel.d.ts +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +16 -0
- package/dist/terrenoApp.js +18 -0
- package/dist/tests/models.d.ts +22 -22
- package/dist/tests/models.js +15 -1
- package/dist/tests/testHelper.d.ts +6 -12
- package/dist/tests.d.ts +1 -0
- package/dist/tests.js +3 -1
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpAdmin.d.ts +58 -0
- package/dist/types/mcpAdmin.js +2 -0
- package/dist/types/mcpOAuth.d.ts +37 -2
- package/dist/types/mcpServiceToken.d.ts +2 -0
- package/e2e/smoke.ts +193 -0
- package/package.json +10 -5
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/adminModelRouter.test.ts +8 -6
- package/src/api.arrayOperations.test.ts +102 -22
- package/src/api.hooks.test.ts +12 -11
- package/src/api.query.test.ts +2 -2
- package/src/api.test.ts +8 -7
- package/src/api.ts +41 -10
- package/src/audit/auditApp.test.ts +1 -1
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/cloudTasksEnqueue.test.ts +19 -14
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/auth.test.ts +21 -7
- package/src/authRecovery.test.ts +33 -10
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/authVerification.test.ts +7 -7
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +490 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +846 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +115 -57
- package/src/betterAuthSetup.ts +457 -38
- package/src/collectionRegistry.test.ts +4 -4
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/frameworkModelNames.test.ts +8 -0
- package/src/frameworkModelNames.ts +4 -0
- package/src/githubAuth.test.ts +11 -11
- package/src/index.ts +38 -0
- package/src/isolated/migrateCliConnect.isolated.ts +3 -2
- package/src/mcp/actionTools.test.ts +11 -5
- package/src/mcp/adminTracking.test.ts +272 -0
- package/src/mcp/adminTracking.ts +104 -0
- package/src/mcp/auth.ts +18 -2
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/mcp/server.ts +67 -4
- package/src/mcp/serviceTokens.test.ts +2 -1
- package/src/mcp/toolGenerator.test.ts +9 -5
- package/src/migrations/cli.test.ts +15 -14
- package/src/migrations/cli.ts +1 -1
- package/src/migrations/generate.test.ts +2 -2
- package/src/migrations/load.test.ts +1 -1
- package/src/migrations/lock.test.ts +8 -3
- package/src/migrations/runner.test.ts +16 -5
- package/src/migrations/schemaCatalog.test.ts +4 -1
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.test.ts +42 -0
- package/src/models/mcpOAuthToken.ts +62 -5
- package/src/models/mcpRequestLog.ts +81 -0
- package/src/models/mcpServiceToken.test.ts +23 -0
- package/src/models/mcpServiceToken.ts +10 -0
- package/src/models/mcpToolSetting.test.ts +69 -0
- package/src/models/mcpToolSetting.ts +138 -0
- package/src/models/versionConfig.ts +2 -0
- package/src/notifications/notificationsApp.test.ts +5 -8
- package/src/notifiers/slackWebApi.test.ts +30 -8
- package/src/openApi.test.ts +4 -4
- package/src/openApiValidator.test.ts +3 -3
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgPermissions.test.ts +2 -2
- package/src/orgs/orgPlugin.test.ts +4 -3
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgSecurityDefects.test.ts +3 -1
- package/src/orgs/organizationSettings.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +104 -3
- package/src/orgs/orgsApp.ts +69 -28
- package/src/permissions.test.ts +2 -2
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
- package/src/rbac/access.ts +4 -1
- package/src/rbac/assertAllowed.test.ts +1 -1
- package/src/rbac/auditModel.ts +10 -2
- package/src/rbac/realtimeAccess.test.ts +3 -2
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +56 -5
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/realtime/realtime.test.ts +35 -31
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/scrubAdminFields.test.ts +1 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/sync/adminWindowMutation.test.ts +4 -3
- package/src/sync/executors.test.ts +1 -1
- package/src/sync/scripts/compactTombstones.test.ts +4 -3
- package/src/sync/sync.test.ts +1 -1
- package/src/sync/syncPhaseC.test.ts +14 -11
- package/src/sync/syncRoutes.test.ts +8 -8
- package/src/sync/syncSeqPlugin.test.ts +1 -2
- package/src/sync/syncSocket.test.ts +5 -4
- package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
- package/src/terrenoApp.migrations.test.ts +8 -7
- package/src/terrenoApp.ts +34 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +189 -0
- package/src/tests/bunSetup.ts +1 -1
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +23 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/tests/testEnv.ts +7 -0
- package/src/tests.ts +1 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpAdmin.ts +80 -0
- package/src/types/mcpOAuth.ts +44 -3
- package/src/types/mcpServiceToken.ts +5 -0
- package/src/webhooks/verifiers/hmac.test.ts +1 -1
- package/tsconfig.typecheck.json +14 -0
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* oauth-proxy across two deploys: a "stable" API that owns the provider's registered callback,
|
|
3
|
+
* and a "preview" API with its own database that shares only the secret. A sign-in started on
|
|
4
|
+
* the preview goes to the provider with stable's callback, stable turns the provider's answer
|
|
5
|
+
* into an encrypted profile and sends it back to the preview, and the preview creates the
|
|
6
|
+
* session and hands it to its bearer-mode web app with a one-time token.
|
|
7
|
+
*/
|
|
8
|
+
import {afterAll, beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
9
|
+
import {once} from "node:events";
|
|
10
|
+
import type {IncomingMessage, Server, ServerResponse} from "node:http";
|
|
11
|
+
import {createServer} from "node:http";
|
|
12
|
+
import type {AddressInfo} from "node:net";
|
|
13
|
+
import {genericOAuth} from "better-auth/plugins";
|
|
14
|
+
import express from "express";
|
|
15
|
+
import mongoose from "mongoose";
|
|
16
|
+
import type {BetterAuthConfig} from "./betterAuth";
|
|
17
|
+
import {createBetterAuth, type MongoClientLike, mountBetterAuthRoutes} from "./betterAuthSetup";
|
|
18
|
+
import {type MockOidcProvider, startMockOidcProvider} from "./tests/mockOidcProvider";
|
|
19
|
+
|
|
20
|
+
const PROVIDER_ID = "mock-oidc";
|
|
21
|
+
const SHARED_SECRET = "shared-secret-at-least-32-characters-long";
|
|
22
|
+
const STABLE_WEB_ORIGIN = "https://app.example.com";
|
|
23
|
+
const PREVIEW_WEB_ORIGIN = "https://deploy-preview-42--example.netlify.app";
|
|
24
|
+
// Sign in with Apple posts its form_post return from this origin.
|
|
25
|
+
const APPLE_ORIGIN = "https://appleid.apple.com";
|
|
26
|
+
const STABLE_DB = "terreno-oauth-proxy-stable";
|
|
27
|
+
const PREVIEW_DB = "terreno-oauth-proxy-preview";
|
|
28
|
+
const AUTH_COLLECTIONS = ["user", "session", "account", "verification"];
|
|
29
|
+
|
|
30
|
+
interface Deploy {
|
|
31
|
+
close: () => Promise<void>;
|
|
32
|
+
/** The API's origin, such as `http://127.0.0.1:41234`. */
|
|
33
|
+
origin: string;
|
|
34
|
+
/** Builds the deploy's Better Auth app once its origin is known. */
|
|
35
|
+
setApp: (app: express.Application) => void;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Listens first, so the Better Auth baseURL can name the real port.
|
|
39
|
+
const startDeploy = async (): Promise<Deploy> => {
|
|
40
|
+
let current: express.Application | undefined;
|
|
41
|
+
const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {
|
|
42
|
+
if (!current) {
|
|
43
|
+
res.statusCode = 503;
|
|
44
|
+
res.end();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
current(req, res);
|
|
48
|
+
});
|
|
49
|
+
server.listen(0, "127.0.0.1");
|
|
50
|
+
await once(server, "listening");
|
|
51
|
+
return {
|
|
52
|
+
close: async (): Promise<void> => {
|
|
53
|
+
server.close();
|
|
54
|
+
await once(server, "close");
|
|
55
|
+
},
|
|
56
|
+
origin: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
|
|
57
|
+
setApp: (app: express.Application): void => {
|
|
58
|
+
current = app;
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// Each deploy gets its own database on the test server, as previews do in Cloud Run.
|
|
64
|
+
const databaseNamed = (name: string): MongoClientLike => {
|
|
65
|
+
const client = (
|
|
66
|
+
mongoose.connection as unknown as {client?: {db: (n: string) => mongoose.mongo.Db}}
|
|
67
|
+
).client;
|
|
68
|
+
if (!client) {
|
|
69
|
+
throw new Error("The test database is not connected");
|
|
70
|
+
}
|
|
71
|
+
return {db: () => client.db(name)};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const countIn = async (dbName: string, collection: string): Promise<number> =>
|
|
75
|
+
databaseNamed(dbName).db().collection(collection).countDocuments();
|
|
76
|
+
|
|
77
|
+
let provider: MockOidcProvider;
|
|
78
|
+
let stable: Deploy;
|
|
79
|
+
let preview: Deploy;
|
|
80
|
+
|
|
81
|
+
const mockProviderPlugin = (): ReturnType<typeof genericOAuth> =>
|
|
82
|
+
genericOAuth({
|
|
83
|
+
config: [
|
|
84
|
+
{
|
|
85
|
+
clientId: "mock-client",
|
|
86
|
+
clientSecret: "mock-secret",
|
|
87
|
+
discoveryUrl: `${provider.issuer}/.well-known/openid-configuration`,
|
|
88
|
+
providerId: PROVIDER_ID,
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const mountDeploy = (deploy: Deploy, dbName: string, config: Partial<BetterAuthConfig>): void => {
|
|
94
|
+
const auth = createBetterAuth({
|
|
95
|
+
config: {
|
|
96
|
+
baseURL: deploy.origin,
|
|
97
|
+
enabled: true,
|
|
98
|
+
// Better Auth skips origin checks when NODE_ENV is "test"; turn them back on so every
|
|
99
|
+
// callbackURL below passes the same check it would in production.
|
|
100
|
+
options: {advanced: {disableOriginCheck: false}},
|
|
101
|
+
plugins: [mockProviderPlugin()],
|
|
102
|
+
secret: SHARED_SECRET,
|
|
103
|
+
...config,
|
|
104
|
+
},
|
|
105
|
+
mongoClient: databaseNamed(dbName),
|
|
106
|
+
});
|
|
107
|
+
const app = express();
|
|
108
|
+
mountBetterAuthRoutes(app, auth);
|
|
109
|
+
deploy.setApp(app);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const fetchManual = (url: string, init: RequestInit = {}): Promise<Response> =>
|
|
113
|
+
fetch(url, {...init, redirect: "manual"});
|
|
114
|
+
|
|
115
|
+
const locationOf = (res: Response): string => {
|
|
116
|
+
const location = res.headers.get("location");
|
|
117
|
+
if (!location) {
|
|
118
|
+
throw new Error(`Expected a redirect, got ${res.status}: no location header`);
|
|
119
|
+
}
|
|
120
|
+
return location;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
interface ProxiedReturn {
|
|
124
|
+
/** The preview URL stable redirected to, carrying the encrypted profile. */
|
|
125
|
+
proxyReturn: URL;
|
|
126
|
+
/** The provider's authorize URL the preview sent the browser to. */
|
|
127
|
+
authorize: URL;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The browser's trip: the preview starts the sign-in, the provider approves, and the provider's
|
|
131
|
+
// redirect lands on stable's registered callback, which answers with a redirect to the preview.
|
|
132
|
+
const runToStableCallback = async (callbackURL: string): Promise<ProxiedReturn> => {
|
|
133
|
+
const start = await fetchManual(
|
|
134
|
+
`${preview.origin}/api/auth/oauth-handoff/start?${new URLSearchParams({
|
|
135
|
+
callbackURL,
|
|
136
|
+
provider: PROVIDER_ID,
|
|
137
|
+
})}`,
|
|
138
|
+
{headers: {"sec-fetch-dest": "document"}}
|
|
139
|
+
);
|
|
140
|
+
expect(start.status).toBe(302);
|
|
141
|
+
const authorize = new URL(locationOf(start));
|
|
142
|
+
expect(authorize.origin).toBe(provider.issuer);
|
|
143
|
+
|
|
144
|
+
const approval = await fetchManual(authorize.toString());
|
|
145
|
+
const callback = new URL(locationOf(approval));
|
|
146
|
+
// The provider only ever sees stable's registered callback.
|
|
147
|
+
expect(callback.origin).toBe(stable.origin);
|
|
148
|
+
expect(callback.pathname).toBe(`/api/auth/callback/${PROVIDER_ID}`);
|
|
149
|
+
|
|
150
|
+
// No cookie from the preview travels to stable: the state rides in the encrypted `state`.
|
|
151
|
+
const stableCallback = await fetchManual(callback.toString());
|
|
152
|
+
expect(stableCallback.status).toBe(302);
|
|
153
|
+
return {authorize, proxyReturn: new URL(locationOf(stableCallback))};
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// `name=value` pairs from a response's set-cookie headers, ready for a cookie request header.
|
|
157
|
+
const cookieHeader = (res: Response): string =>
|
|
158
|
+
res.headers
|
|
159
|
+
.getSetCookie()
|
|
160
|
+
.map((entry) => entry.split(";")[0])
|
|
161
|
+
.join("; ");
|
|
162
|
+
|
|
163
|
+
interface SocialStart {
|
|
164
|
+
cookie: string;
|
|
165
|
+
url: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The web app's own `signIn.social` call (POST, JSON), as a cookie-mode client makes it.
|
|
169
|
+
const postSignInSocial = async (
|
|
170
|
+
apiOrigin: string,
|
|
171
|
+
webOrigin: string,
|
|
172
|
+
callbackURL: string
|
|
173
|
+
): Promise<SocialStart> => {
|
|
174
|
+
const res = await fetch(`${apiOrigin}/api/auth/sign-in/social`, {
|
|
175
|
+
body: JSON.stringify({callbackURL, provider: PROVIDER_ID}),
|
|
176
|
+
headers: {"content-type": "application/json", origin: webOrigin},
|
|
177
|
+
method: "POST",
|
|
178
|
+
});
|
|
179
|
+
expect(res.status).toBe(200);
|
|
180
|
+
const body = (await res.json()) as {url: string};
|
|
181
|
+
return {cookie: cookieHeader(res), url: body.url};
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const verifyOnPreview = (token: string): Promise<Response> =>
|
|
185
|
+
fetch(`${preview.origin}/api/auth/one-time-token/verify`, {
|
|
186
|
+
body: JSON.stringify({token}),
|
|
187
|
+
headers: {"content-type": "application/json", origin: PREVIEW_WEB_ORIGIN},
|
|
188
|
+
method: "POST",
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
const ottFrom = (location: string): string =>
|
|
192
|
+
new URLSearchParams(new URL(location).hash.slice(1)).get("ott") ?? "";
|
|
193
|
+
|
|
194
|
+
beforeAll(async () => {
|
|
195
|
+
provider = await startMockOidcProvider();
|
|
196
|
+
stable = await startDeploy();
|
|
197
|
+
preview = await startDeploy();
|
|
198
|
+
// Stable runs the plugin too, naming itself: its callback hook is what forwards a preview's
|
|
199
|
+
// return. Naming itself makes its own sign-ins skip the proxy, so they keep the state cookie.
|
|
200
|
+
mountDeploy(stable, STABLE_DB, {
|
|
201
|
+
oauthHandoff: {webOrigins: [STABLE_WEB_ORIGIN]},
|
|
202
|
+
oauthProxy: {productionURL: stable.origin},
|
|
203
|
+
trustedOrigins: [STABLE_WEB_ORIGIN, APPLE_ORIGIN],
|
|
204
|
+
});
|
|
205
|
+
mountDeploy(preview, PREVIEW_DB, {
|
|
206
|
+
oauthHandoff: {callbackPaths: ["/", "/after"], webOrigins: [PREVIEW_WEB_ORIGIN]},
|
|
207
|
+
oauthProxy: {productionURL: stable.origin},
|
|
208
|
+
trustedOrigins: [PREVIEW_WEB_ORIGIN],
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
afterAll(async () => {
|
|
213
|
+
await preview?.close();
|
|
214
|
+
await stable?.close();
|
|
215
|
+
await provider?.close();
|
|
216
|
+
await databaseNamed(STABLE_DB).db().dropDatabase();
|
|
217
|
+
await databaseNamed(PREVIEW_DB).db().dropDatabase();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
beforeEach(async () => {
|
|
221
|
+
provider.setUser({
|
|
222
|
+
email: `proxy-${Math.random().toString(36).slice(2)}@example.com`,
|
|
223
|
+
id: `proxy-${Math.random().toString(36).slice(2)}`,
|
|
224
|
+
name: "Proxy User",
|
|
225
|
+
});
|
|
226
|
+
for (const dbName of [STABLE_DB, PREVIEW_DB]) {
|
|
227
|
+
for (const collection of AUTH_COLLECTIONS) {
|
|
228
|
+
await databaseNamed(dbName).db().collection(collection).deleteMany({});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
describe("oauthProxy between a preview and the stable deploy", () => {
|
|
234
|
+
it("returns a preview-started sign-in through stable's callback with a one-time token", async () => {
|
|
235
|
+
const {authorize, proxyReturn} = await runToStableCallback(`${PREVIEW_WEB_ORIGIN}/after`);
|
|
236
|
+
|
|
237
|
+
expect(authorize.searchParams.get("redirect_uri")).toBe(
|
|
238
|
+
`${stable.origin}/api/auth/callback/${PROVIDER_ID}`
|
|
239
|
+
);
|
|
240
|
+
expect(proxyReturn.origin).toBe(preview.origin);
|
|
241
|
+
expect(proxyReturn.pathname).toBe(`/api/auth/callback/${PROVIDER_ID}/oauth-proxy`);
|
|
242
|
+
expect(proxyReturn.searchParams.get("callbackURL")).toBe(`${PREVIEW_WEB_ORIGIN}/after`);
|
|
243
|
+
expect(proxyReturn.searchParams.get("profile")).toBeTruthy();
|
|
244
|
+
// Stable finished the provider's code exchange without writing anything of its own.
|
|
245
|
+
for (const collection of AUTH_COLLECTIONS) {
|
|
246
|
+
expect(await countIn(STABLE_DB, collection)).toBe(0);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const finish = await fetchManual(proxyReturn.toString());
|
|
250
|
+
expect(finish.status).toBe(302);
|
|
251
|
+
const location = locationOf(finish);
|
|
252
|
+
expect(location).toStartWith(`${PREVIEW_WEB_ORIGIN}/after#ott=`);
|
|
253
|
+
// The bearer web app gets its session from the token, not from a cookie on the preview API.
|
|
254
|
+
const cookies = finish.headers.getSetCookie();
|
|
255
|
+
expect(cookies.some((cookie) => cookie.includes("session_token="))).toBe(false);
|
|
256
|
+
|
|
257
|
+
const verified = await verifyOnPreview(ottFrom(location));
|
|
258
|
+
expect(verified.status).toBe(200);
|
|
259
|
+
const bearer = verified.headers.get("set-auth-token") ?? "";
|
|
260
|
+
expect(bearer).toBeTruthy();
|
|
261
|
+
const session = await fetch(`${preview.origin}/api/auth/get-session`, {
|
|
262
|
+
headers: {authorization: `Bearer ${bearer}`},
|
|
263
|
+
});
|
|
264
|
+
const body = (await session.json()) as {user: {email: string}};
|
|
265
|
+
expect(body.user.email).toStartWith("proxy-");
|
|
266
|
+
|
|
267
|
+
// The user, account and session live only in the preview's database.
|
|
268
|
+
expect(await countIn(PREVIEW_DB, "user")).toBe(1);
|
|
269
|
+
expect(await countIn(PREVIEW_DB, "account")).toBe(1);
|
|
270
|
+
expect(await countIn(STABLE_DB, "user")).toBe(0);
|
|
271
|
+
expect(await countIn(STABLE_DB, "session")).toBe(0);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it("proxies a form_post return (Apple's response_mode) from a trusted provider origin", async () => {
|
|
275
|
+
const start = await fetchManual(
|
|
276
|
+
`${preview.origin}/api/auth/oauth-handoff/start?${new URLSearchParams({
|
|
277
|
+
callbackURL: `${PREVIEW_WEB_ORIGIN}/`,
|
|
278
|
+
provider: PROVIDER_ID,
|
|
279
|
+
})}`,
|
|
280
|
+
{headers: {"sec-fetch-dest": "document"}}
|
|
281
|
+
);
|
|
282
|
+
const approval = new URL(locationOf(await fetchManual(locationOf(start))));
|
|
283
|
+
|
|
284
|
+
// Apple posts `code` and `state` from appleid.apple.com to the registered callback. The
|
|
285
|
+
// state rides in the encrypted package, so no SameSite=Lax cookie is needed; a SameSite=None
|
|
286
|
+
// cookie the browser does send makes Better Auth check the POST's Origin, which is why the
|
|
287
|
+
// stable deploy lists appleid.apple.com in trustedOrigins.
|
|
288
|
+
const posted = await fetchManual(`${stable.origin}/api/auth/callback/${PROVIDER_ID}`, {
|
|
289
|
+
body: new URLSearchParams({
|
|
290
|
+
code: approval.searchParams.get("code") ?? "",
|
|
291
|
+
state: approval.searchParams.get("state") ?? "",
|
|
292
|
+
}).toString(),
|
|
293
|
+
headers: {
|
|
294
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
295
|
+
cookie: "__Secure-better-auth.session_token=unrelated",
|
|
296
|
+
origin: APPLE_ORIGIN,
|
|
297
|
+
"sec-fetch-site": "cross-site",
|
|
298
|
+
},
|
|
299
|
+
method: "POST",
|
|
300
|
+
});
|
|
301
|
+
expect(posted.status).toBe(302);
|
|
302
|
+
const proxyReturn = new URL(locationOf(posted));
|
|
303
|
+
expect(proxyReturn.origin).toBe(preview.origin);
|
|
304
|
+
|
|
305
|
+
const finish = await fetchManual(proxyReturn.toString());
|
|
306
|
+
|
|
307
|
+
expect(locationOf(finish)).toStartWith(`${PREVIEW_WEB_ORIGIN}/#ott=`);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("hands off on the deprecated /oauth-proxy-callback path too", async () => {
|
|
311
|
+
const {proxyReturn} = await runToStableCallback(`${PREVIEW_WEB_ORIGIN}/`);
|
|
312
|
+
const legacy = new URL(`${preview.origin}/api/auth/oauth-proxy-callback`);
|
|
313
|
+
legacy.search = proxyReturn.search;
|
|
314
|
+
|
|
315
|
+
const finish = await fetchManual(legacy.toString());
|
|
316
|
+
|
|
317
|
+
expect(finish.status).toBe(302);
|
|
318
|
+
const location = locationOf(finish);
|
|
319
|
+
expect(location).toStartWith(`${PREVIEW_WEB_ORIGIN}/#ott=`);
|
|
320
|
+
const verified = await verifyOnPreview(ottFrom(location));
|
|
321
|
+
expect(verified.status).toBe(200);
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
it("refuses a profile replayed after its sign-in finished", async () => {
|
|
325
|
+
const {proxyReturn} = await runToStableCallback(`${PREVIEW_WEB_ORIGIN}/after`);
|
|
326
|
+
const first = await fetchManual(proxyReturn.toString());
|
|
327
|
+
expect(locationOf(first)).toContain("#ott=");
|
|
328
|
+
|
|
329
|
+
const replay = await fetchManual(proxyReturn.toString());
|
|
330
|
+
|
|
331
|
+
expect(replay.status).toBe(302);
|
|
332
|
+
expect(locationOf(replay)).not.toContain("ott=");
|
|
333
|
+
expect(locationOf(replay)).toContain("error=state_mismatch");
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
it("refuses a profile from a deploy with a different secret", async () => {
|
|
337
|
+
const stranger = await startDeploy();
|
|
338
|
+
try {
|
|
339
|
+
mountDeploy(stranger, PREVIEW_DB, {
|
|
340
|
+
oauthHandoff: {webOrigins: [PREVIEW_WEB_ORIGIN]},
|
|
341
|
+
oauthProxy: {productionURL: stable.origin},
|
|
342
|
+
secret: "another-secret-at-least-32-characters-long",
|
|
343
|
+
trustedOrigins: [PREVIEW_WEB_ORIGIN],
|
|
344
|
+
});
|
|
345
|
+
const {proxyReturn} = await runToStableCallback(`${PREVIEW_WEB_ORIGIN}/after`);
|
|
346
|
+
const forged = new URL(`${stranger.origin}${proxyReturn.pathname}`);
|
|
347
|
+
forged.search = proxyReturn.search;
|
|
348
|
+
|
|
349
|
+
const finish = await fetchManual(forged.toString());
|
|
350
|
+
|
|
351
|
+
expect(finish.status).toBe(302);
|
|
352
|
+
expect(locationOf(finish)).toContain("error=invalid_profile");
|
|
353
|
+
expect(locationOf(finish)).not.toContain("ott=");
|
|
354
|
+
} finally {
|
|
355
|
+
await stranger.close();
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
it("returns a sign-in started on stable straight to its web app, with the state cookie", async () => {
|
|
360
|
+
const start = await fetchManual(
|
|
361
|
+
`${stable.origin}/api/auth/oauth-handoff/start?${new URLSearchParams({
|
|
362
|
+
callbackURL: `${STABLE_WEB_ORIGIN}/`,
|
|
363
|
+
provider: PROVIDER_ID,
|
|
364
|
+
})}`,
|
|
365
|
+
{headers: {"sec-fetch-dest": "document"}}
|
|
366
|
+
);
|
|
367
|
+
const approval = await fetchManual(locationOf(start));
|
|
368
|
+
const callbackURL = locationOf(approval);
|
|
369
|
+
|
|
370
|
+
// Without the browser's state cookie, Better Auth refuses the return (login CSRF guard).
|
|
371
|
+
const withoutCookie = await fetchManual(callbackURL);
|
|
372
|
+
expect(locationOf(withoutCookie)).toContain("error=state_mismatch");
|
|
373
|
+
expect(locationOf(withoutCookie)).not.toContain("ott=");
|
|
374
|
+
|
|
375
|
+
const finish = await fetchManual(callbackURL, {headers: {cookie: cookieHeader(start)}});
|
|
376
|
+
|
|
377
|
+
// No hop through oauth-proxy's completion, which would skip the state-cookie check.
|
|
378
|
+
expect(locationOf(finish)).toStartWith(`${STABLE_WEB_ORIGIN}/#ott=`);
|
|
379
|
+
expect(await countIn(STABLE_DB, "user")).toBe(1);
|
|
380
|
+
expect(await countIn(PREVIEW_DB, "user")).toBe(0);
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
it("leaves a direct sign-in on stable unproxied, even on another host name", async () => {
|
|
384
|
+
// A Cloud Run tag URL (prod---...) reaches the same server under another host.
|
|
385
|
+
const otherHost = stable.origin.replace("127.0.0.1", "localhost");
|
|
386
|
+
const start = await postSignInSocial(otherHost, STABLE_WEB_ORIGIN, `${STABLE_WEB_ORIGIN}/home`);
|
|
387
|
+
const authorize = new URL(start.url);
|
|
388
|
+
expect(authorize.searchParams.get("redirect_uri")).toBe(
|
|
389
|
+
`${stable.origin}/api/auth/callback/${PROVIDER_ID}`
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
const approval = await fetchManual(authorize.toString());
|
|
393
|
+
const finish = await fetchManual(locationOf(approval), {headers: {cookie: start.cookie}});
|
|
394
|
+
|
|
395
|
+
expect(locationOf(finish)).toBe(`${STABLE_WEB_ORIGIN}/home`);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
it("sends a direct sign-in on the preview through stable's callback", async () => {
|
|
399
|
+
const start = await postSignInSocial(
|
|
400
|
+
preview.origin,
|
|
401
|
+
PREVIEW_WEB_ORIGIN,
|
|
402
|
+
`${PREVIEW_WEB_ORIGIN}/home`
|
|
403
|
+
);
|
|
404
|
+
const authorize = new URL(start.url);
|
|
405
|
+
expect(authorize.searchParams.get("redirect_uri")).toBe(
|
|
406
|
+
`${stable.origin}/api/auth/callback/${PROVIDER_ID}`
|
|
407
|
+
);
|
|
408
|
+
|
|
409
|
+
const approval = await fetchManual(authorize.toString());
|
|
410
|
+
const proxyReturn = new URL(locationOf(await fetchManual(locationOf(approval))));
|
|
411
|
+
expect(proxyReturn.origin).toBe(preview.origin);
|
|
412
|
+
const finish = await fetchManual(proxyReturn.toString());
|
|
413
|
+
|
|
414
|
+
// /home is not a handoff page, so the cookie client gets its session cookie and no token.
|
|
415
|
+
expect(locationOf(finish)).toBe(`${PREVIEW_WEB_ORIGIN}/home`);
|
|
416
|
+
expect(finish.headers.getSetCookie().some((cookie) => cookie.includes("session_token="))).toBe(
|
|
417
|
+
true
|
|
418
|
+
);
|
|
419
|
+
expect(await countIn(PREVIEW_DB, "user")).toBe(1);
|
|
420
|
+
});
|
|
421
|
+
});
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Better Auth's `POST {basePath}/reset-password` over HTTP with a user model: Terreno copies the
|
|
3
|
+
* new password to the app User's passport hash (only when it already has one) and bumps
|
|
4
|
+
* `tokenEpoch`. Better Auth has already
|
|
5
|
+
* read the request body by the time its `onPasswordReset` hook runs, so the password must come
|
|
6
|
+
* from the parsed endpoint body, not from the request.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
10
|
+
import supertest from "supertest";
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
access,
|
|
14
|
+
buildApp,
|
|
15
|
+
captureMail,
|
|
16
|
+
resetAccountSecurityState,
|
|
17
|
+
resetTokenFrom,
|
|
18
|
+
SecurityUser,
|
|
19
|
+
signInWithPassword,
|
|
20
|
+
signUp,
|
|
21
|
+
} from "./tests/accountSecurityTestApp";
|
|
22
|
+
import {newStubIdentity, stubGoogleIdTokenOptions} from "./tests/betterAuthStubs";
|
|
23
|
+
|
|
24
|
+
const NEW_PASSWORD = "new-password-654321";
|
|
25
|
+
|
|
26
|
+
interface PassportProbe {
|
|
27
|
+
authenticate: (password: string) => Promise<{user?: unknown}>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether `password` verifies against the app User's passport (JWT) hash. */
|
|
31
|
+
const jwtPasswordMatches = async (userId: string, password: string): Promise<boolean> => {
|
|
32
|
+
const stored = await SecurityUser.collection
|
|
33
|
+
.find({_id: new SecurityUser.base.Types.ObjectId(userId)})
|
|
34
|
+
.limit(1)
|
|
35
|
+
.next();
|
|
36
|
+
if (!stored) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
const probe = SecurityUser.hydrate(stored) as unknown as PassportProbe;
|
|
40
|
+
const result = await probe.authenticate(password);
|
|
41
|
+
return Boolean(result.user);
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const OLD_JWT_PASSWORD = "old-jwt-password-123";
|
|
45
|
+
|
|
46
|
+
/** Gives the app User a legacy JWT (passport) password, as a dual-enrolled account has. */
|
|
47
|
+
const giveJwtPassword = async (userId: string): Promise<void> => {
|
|
48
|
+
const user = (await SecurityUser.findById(userId)) as unknown as {
|
|
49
|
+
save: () => Promise<unknown>;
|
|
50
|
+
setPassword: (password: string) => Promise<unknown>;
|
|
51
|
+
};
|
|
52
|
+
await user.setPassword(OLD_JWT_PASSWORD);
|
|
53
|
+
await user.save();
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
describe("Better Auth password reset over HTTP", () => {
|
|
57
|
+
beforeAll(async () => {
|
|
58
|
+
await access.roles.seedDefaults();
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
beforeEach(async () => {
|
|
62
|
+
await resetAccountSecurityState();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("resets the password, syncs the JWT hash, and bumps tokenEpoch", async () => {
|
|
66
|
+
const mail = captureMail();
|
|
67
|
+
const {app} = buildApp({config: mail.config});
|
|
68
|
+
const user = await signUp(app, "http-reset");
|
|
69
|
+
await giveJwtPassword(user.id);
|
|
70
|
+
mail.sent.length = 0;
|
|
71
|
+
|
|
72
|
+
const request = await supertest(app)
|
|
73
|
+
.post("/api/auth/request-password-reset")
|
|
74
|
+
.set("content-type", "application/json")
|
|
75
|
+
.send({email: user.email});
|
|
76
|
+
expect(request.status).toBe(200);
|
|
77
|
+
const resetMails = mail.sent.filter((sent) => sent.subject === "Reset your password");
|
|
78
|
+
expect(resetMails).toHaveLength(1);
|
|
79
|
+
const token = resetTokenFrom(resetMails[0]);
|
|
80
|
+
expect(token).not.toBe("");
|
|
81
|
+
|
|
82
|
+
const reset = await supertest(app)
|
|
83
|
+
.post("/api/auth/reset-password")
|
|
84
|
+
.set("content-type", "application/json")
|
|
85
|
+
.send({newPassword: NEW_PASSWORD, token});
|
|
86
|
+
|
|
87
|
+
expect(reset.status).toBe(200);
|
|
88
|
+
expect(reset.body).toEqual({status: true});
|
|
89
|
+
const signIn = await supertest(app)
|
|
90
|
+
.post("/api/auth/sign-in/email")
|
|
91
|
+
.set("content-type", "application/json")
|
|
92
|
+
.send({email: user.email, password: NEW_PASSWORD});
|
|
93
|
+
expect(signIn.status).toBe(200);
|
|
94
|
+
expect((await signInWithPassword(app, user.email)).status).toBe(401);
|
|
95
|
+
const appUser = await SecurityUser.findById(user.id);
|
|
96
|
+
expect(appUser?.tokenEpoch).toBe(1);
|
|
97
|
+
expect(await jwtPasswordMatches(user.id, NEW_PASSWORD)).toBe(true);
|
|
98
|
+
expect(await jwtPasswordMatches(user.id, OLD_JWT_PASSWORD)).toBe(false);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("syncs the JWT hash for a direct auth.api.resetPassword call with no request", async () => {
|
|
102
|
+
const mail = captureMail();
|
|
103
|
+
const {app, betterAuthApp} = buildApp({config: mail.config});
|
|
104
|
+
const user = await signUp(app, "direct-reset");
|
|
105
|
+
await giveJwtPassword(user.id);
|
|
106
|
+
mail.sent.length = 0;
|
|
107
|
+
await supertest(app)
|
|
108
|
+
.post("/api/auth/request-password-reset")
|
|
109
|
+
.set("content-type", "application/json")
|
|
110
|
+
.send({email: user.email})
|
|
111
|
+
.expect(200);
|
|
112
|
+
const token = resetTokenFrom(mail.sent[mail.sent.length - 1]);
|
|
113
|
+
|
|
114
|
+
const result = await betterAuthApp.ensureAuth().api.resetPassword({
|
|
115
|
+
body: {newPassword: NEW_PASSWORD, token},
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
expect(result).toEqual({status: true});
|
|
119
|
+
expect((await SecurityUser.findById(user.id))?.tokenEpoch).toBe(1);
|
|
120
|
+
expect(await jwtPasswordMatches(user.id, NEW_PASSWORD)).toBe(true);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("does not give a social-only account a JWT password", async () => {
|
|
124
|
+
const identity = newStubIdentity("social-reset");
|
|
125
|
+
const mail = captureMail();
|
|
126
|
+
const {app} = buildApp({
|
|
127
|
+
config: {
|
|
128
|
+
...mail.config,
|
|
129
|
+
googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
|
|
130
|
+
options: stubGoogleIdTokenOptions(identity),
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
await supertest(app)
|
|
134
|
+
.post("/api/auth/sign-in/social")
|
|
135
|
+
.send({idToken: {token: "stub-id-token"}, provider: "google"})
|
|
136
|
+
.expect(200);
|
|
137
|
+
await supertest(app)
|
|
138
|
+
.post("/api/auth/request-password-reset")
|
|
139
|
+
.set("content-type", "application/json")
|
|
140
|
+
.send({email: identity.email})
|
|
141
|
+
.expect(200);
|
|
142
|
+
const token = resetTokenFrom(mail.sent[mail.sent.length - 1]);
|
|
143
|
+
|
|
144
|
+
await supertest(app)
|
|
145
|
+
.post("/api/auth/reset-password")
|
|
146
|
+
.set("content-type", "application/json")
|
|
147
|
+
.send({newPassword: NEW_PASSWORD, token})
|
|
148
|
+
.expect(200);
|
|
149
|
+
|
|
150
|
+
// Better Auth takes the new password; JWT login, which has no second factor, does not.
|
|
151
|
+
await supertest(app)
|
|
152
|
+
.post("/api/auth/sign-in/email")
|
|
153
|
+
.set("content-type", "application/json")
|
|
154
|
+
.send({email: identity.email, password: NEW_PASSWORD})
|
|
155
|
+
.expect(200);
|
|
156
|
+
const login = await supertest(app)
|
|
157
|
+
.post("/auth/login")
|
|
158
|
+
.send({email: identity.email, password: NEW_PASSWORD});
|
|
159
|
+
expect(login.status).toBe(401);
|
|
160
|
+
const stored = await SecurityUser.collection.findOne({email: identity.email});
|
|
161
|
+
expect(stored?.hash).toBeUndefined();
|
|
162
|
+
expect(stored?.tokenEpoch).toBe(1);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("refuses a reused reset token and leaves tokenEpoch alone", async () => {
|
|
166
|
+
const mail = captureMail();
|
|
167
|
+
const {app} = buildApp({config: mail.config});
|
|
168
|
+
const user = await signUp(app, "http-reset-reuse");
|
|
169
|
+
mail.sent.length = 0;
|
|
170
|
+
await supertest(app)
|
|
171
|
+
.post("/api/auth/request-password-reset")
|
|
172
|
+
.set("content-type", "application/json")
|
|
173
|
+
.send({email: user.email})
|
|
174
|
+
.expect(200);
|
|
175
|
+
const token = resetTokenFrom(mail.sent[mail.sent.length - 1]);
|
|
176
|
+
await supertest(app)
|
|
177
|
+
.post("/api/auth/reset-password")
|
|
178
|
+
.set("content-type", "application/json")
|
|
179
|
+
.send({newPassword: NEW_PASSWORD, token})
|
|
180
|
+
.expect(200);
|
|
181
|
+
|
|
182
|
+
const reuse = await supertest(app)
|
|
183
|
+
.post("/api/auth/reset-password")
|
|
184
|
+
.set("content-type", "application/json")
|
|
185
|
+
.send({newPassword: "another-password-1", token});
|
|
186
|
+
|
|
187
|
+
expect(reuse.status).toBe(400);
|
|
188
|
+
expect((await SecurityUser.findById(user.id))?.tokenEpoch).toBe(1);
|
|
189
|
+
});
|
|
190
|
+
});
|