diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e9ca9d9..688cd713 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ The file format of it is based on [Keep a Changelog](http://keepachangelog.com/e For public Changelog covering all changes done to Pipedrive’s API, webhooks and app extensions platforms, see [public Changelog](https://pipedrive.readme.io/docs/changelog) with discussion area in [Developers Community](https://devcommunity.pipedrive.com/c/documentation/changelog/19). ## [Unreleased] +### Added +- Documented new `track_open` and `track_click` fields on the Person object (enum: `no_preference_set`, `consent_given`, `consent_declined`). They are returned and accepted only if the company has the "Email tracking consent" setting enabled. +### Changed +- Updated v2 Persons endpoints to include the new fields: `GET /api/v2/persons`, `GET /api/v2/persons/{id}`, `POST /api/v2/persons` and `PATCH /api/v2/persons/{id}`. The `include_fields` query parameter now also accepts `track_open` and `track_click`. +- Added `email_tracking_preference_change` to the possible values of the `items` query parameter of `GET /v1/persons/{id}/flow` and `GET /v1/deals/{id}/flow`, and updated the description of `GET /v1/personFields` (`getPersonFields`) to mention the new fields. ## [36.4.0] - 2026-11-25 ### Added diff --git a/README.md b/README.md index f617ee84..d59b8322 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,22 @@ To obtain user's consent, you must redirect the user to the authorization page. const authUrl = oauth2.authorizationUrl; ``` +To add a `state` value (recommended, to protect against CSRF) or PKCE parameters, use `getAuthorizationUrl()` instead. See [Using PKCE](#using-pkce). + +```typescript +import { randomUUID } from 'crypto'; + +// generate an unpredictable state per login and keep it until the user comes back +const state = randomUUID(); +req.session.oauthState = state; +const authUrl = oauth2.getAuthorizationUrl({ state }); + +// in the redirect URI handler, reject the callback unless the state matches +if (!req.session.oauthState || req.query.state !== req.session.oauthState) { + throw new Error('Invalid OAuth state'); +} +``` + #### 2. Handle the OAuth server response Once the user responds to the consent request, the OAuth 2.0 server responds to your application's access request by using the URL specified in the request. @@ -130,6 +146,34 @@ const token = await oauth2.authorize(code); The Node.js SDK supports only promises. So, the authorize call returns a promise. +### Using PKCE + +PKCE ([RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)) protects the authorization code from being used by anyone other than the app that requested it. PKCE is optional unless your app requires it, and then the `S256` method must be used. + +1. Generate a code verifier and its code challenge, and keep the verifier (for example, in the user's session) until the user comes back to your redirect URI. +2. Send the code challenge to the authorization page. +3. Send the code verifier when you exchange the authorization code. + +```typescript +import { randomUUID } from 'crypto'; + +const state = randomUUID(); +const { codeVerifier, codeChallenge } = await OAuth2Configuration.generatePkce(); +req.session.oauthState = state; +req.session.codeVerifier = codeVerifier; + +// codeChallengeMethod defaults to 'S256' +const authUrl = oauth2.getAuthorizationUrl({ state, codeChallenge }); + +// later, in the redirect URI handler +if (!req.session.oauthState || req.query.state !== req.session.oauthState) { + throw new Error('Invalid OAuth state'); +} +const token = await oauth2.authorize(req.query.code, req.session.codeVerifier); +``` + +`generatePkce()` uses the Web Crypto API (`globalThis.crypto`), available in Node.js 19 and later. + ### Refreshing token Access tokens may expire after sometime, if it necessary you can do it manually. diff --git a/src/versions/v1/configuration.ts b/src/versions/v1/configuration.ts index 0038a274..d0b3da56 100644 --- a/src/versions/v1/configuration.ts +++ b/src/versions/v1/configuration.ts @@ -35,6 +35,22 @@ export interface Parameters { export type ParamKey = keyof Parameters; +export type CodeChallengeMethod = 'S256' | 'plain'; + +export interface AuthorizationUrlParameters { + /** Opaque value returned unchanged to the redirect URI. Use it to protect against CSRF. */ + state?: string; + /** PKCE code challenge derived from the code verifier. See `OAuth2Configuration.generatePkce()`. */ + codeChallenge?: string; + /** PKCE code challenge method. Sent only when `codeChallenge` is set. Defaults to `S256`. */ + codeChallengeMethod?: CodeChallengeMethod; +} + +export type PkcePair = { + codeVerifier: string; + codeChallenge: string; +} + export class OAuth2Configuration { public host: string; public clientId: string; @@ -68,6 +84,50 @@ export class OAuth2Configuration { }&redirect_uri=${encodeURIComponent(this.redirectUri)}`; } + /** + * Builds the URL of the authorization page, optionally with `state` and PKCE parameters. + * @param {AuthorizationUrlParameters} params Optional `state`, `codeChallenge` and `codeChallengeMethod`. + * @returns {String} The authorization page URL. + */ + public getAuthorizationUrl(params: AuthorizationUrlParameters = {}): string { + const { state, codeChallenge, codeChallengeMethod = 'S256' } = params; + const query: Record = { + client_id: this.clientId, + redirect_uri: this.redirectUri, + response_type: 'code', + }; + + if (state) { + query.state = state; + } + + if (codeChallenge) { + query.code_challenge = codeChallenge; + query.code_challenge_method = codeChallengeMethod; + } + + return `${this.host}/oauth/authorize?${stringify(query)}`; + } + + /** + * Generates a PKCE code verifier and its S256 code challenge (RFC 7636). + * Send `codeChallenge` with `getAuthorizationUrl()`, keep `codeVerifier` and pass it to `authorize()`. + * @returns {Promise} The code verifier and code challenge, both base64url encoded. + */ + public static async generatePkce(): Promise { + const webCrypto = globalThis.crypto; + + if (!webCrypto?.subtle) { + throw new Error("PKCE generation requires the Web Crypto API (globalThis.crypto)."); + } + + const codeVerifier = Buffer.from(webCrypto.getRandomValues(new Uint8Array(32))).toString("base64url"); + const digest = await webCrypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier)); + const codeChallenge = Buffer.from(digest).toString("base64url"); + + return { codeVerifier, codeChallenge }; + } + public getAccessToken = async (): Promise => { if (this.shouldRefreshToken()) { const newToken = await this.tokenRefresh(); @@ -86,9 +146,10 @@ export class OAuth2Configuration { /** * Authorizes the authorization code sent by the server and returns OAuth 2 token. * @param {String} code The authorization code sent by the OAuth server. + * @param {String} codeVerifier The PKCE code verifier. Required if a code challenge was sent to the authorization page. * @returns {Object} The OAuth 2 token. */ - public authorize = async (code: string): Promise => { + public authorize = async (code: string, codeVerifier?: string): Promise => { if (!code) { throw new Error("Authorization failed. Authorization code is not set."); } @@ -105,6 +166,7 @@ export class OAuth2Configuration { code, redirect_uri: this.redirectUri, grant_type: "authorization_code", + ...(codeVerifier ? { code_verifier: codeVerifier } : {}), }), { headers: { diff --git a/src/versions/v2/configuration.ts b/src/versions/v2/configuration.ts index 9e794930..b4dd4f4e 100644 --- a/src/versions/v2/configuration.ts +++ b/src/versions/v2/configuration.ts @@ -35,6 +35,22 @@ export interface Parameters { export type ParamKey = keyof Parameters; +export type CodeChallengeMethod = 'S256' | 'plain'; + +export interface AuthorizationUrlParameters { + /** Opaque value returned unchanged to the redirect URI. Use it to protect against CSRF. */ + state?: string; + /** PKCE code challenge derived from the code verifier. See `OAuth2Configuration.generatePkce()`. */ + codeChallenge?: string; + /** PKCE code challenge method. Sent only when `codeChallenge` is set. Defaults to `S256`. */ + codeChallengeMethod?: CodeChallengeMethod; +} + +export type PkcePair = { + codeVerifier: string; + codeChallenge: string; +} + export class OAuth2Configuration { public host: string; public clientId: string; @@ -68,6 +84,50 @@ export class OAuth2Configuration { }&redirect_uri=${encodeURIComponent(this.redirectUri)}`; } + /** + * Builds the URL of the authorization page, optionally with `state` and PKCE parameters. + * @param {AuthorizationUrlParameters} params Optional `state`, `codeChallenge` and `codeChallengeMethod`. + * @returns {String} The authorization page URL. + */ + public getAuthorizationUrl(params: AuthorizationUrlParameters = {}): string { + const { state, codeChallenge, codeChallengeMethod = 'S256' } = params; + const query: Record = { + client_id: this.clientId, + redirect_uri: this.redirectUri, + response_type: 'code', + }; + + if (state) { + query.state = state; + } + + if (codeChallenge) { + query.code_challenge = codeChallenge; + query.code_challenge_method = codeChallengeMethod; + } + + return `${this.host}/oauth/authorize?${stringify(query)}`; + } + + /** + * Generates a PKCE code verifier and its S256 code challenge (RFC 7636). + * Send `codeChallenge` with `getAuthorizationUrl()`, keep `codeVerifier` and pass it to `authorize()`. + * @returns {Promise} The code verifier and code challenge, both base64url encoded. + */ + public static async generatePkce(): Promise { + const webCrypto = globalThis.crypto; + + if (!webCrypto?.subtle) { + throw new Error("PKCE generation requires the Web Crypto API (globalThis.crypto)."); + } + + const codeVerifier = Buffer.from(webCrypto.getRandomValues(new Uint8Array(32))).toString("base64url"); + const digest = await webCrypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier)); + const codeChallenge = Buffer.from(digest).toString("base64url"); + + return { codeVerifier, codeChallenge }; + } + public getAccessToken = async (): Promise => { if (this.shouldRefreshToken()) { const newToken = await this.tokenRefresh(); @@ -86,9 +146,10 @@ export class OAuth2Configuration { /** * Authorizes the authorization code sent by the server and returns OAuth 2 token. * @param {String} code The authorization code sent by the OAuth server. + * @param {String} codeVerifier The PKCE code verifier. Required if a code challenge was sent to the authorization page. * @returns {Object} The OAuth 2 token. */ - public authorize = async (code: string): Promise => { + public authorize = async (code: string, codeVerifier?: string): Promise => { if (!code) { throw new Error("Authorization failed. Authorization code is not set."); } @@ -105,6 +166,7 @@ export class OAuth2Configuration { code, redirect_uri: this.redirectUri, grant_type: "authorization_code", + ...(codeVerifier ? { code_verifier: codeVerifier } : {}), }), { headers: {