# @theorchard/backend-ts-pdp-sdk

## 3.1.0

### Minor Changes

- PP-1534 Run pnpm generate:models to get pdp models

## 3.0.0

### Major Changes

#### BREAKING CHANGE

- Add `UnauthenticatedException` exception for distinct authentication failure handling.

**What Changed:**

1. **New Exception Class**: Introduced `UnauthenticatedException` which is thrown when the ows-pdp returns a 401 (
   Unauthorized) status code.

2. **Authentication Errors Always Propagate**: When a 401 response is received from the ows-pdp,
   `UnauthenticatedException` is now always thrown and propagated to the caller, **regardless of
   the `raiseWhenUnauthorized` flag**. This ensures authentication failures (invalid/missing credentials) are handled
   distinctly from authorization failures (insufficient permissions).

**Migration Guide:**

Before:

```typescript
try {
  const authorized = await pdpAuthorizationBackend.isAuthorized({
    action: "view",
    resourceId: "123",
    resourceType: "audience",
    resourceGetter: myResourceGetter,
    raiseWhenUnauthorized: false, // Would suppress all errors
  });
} catch (error) {
  // Generic error handling
}
```

After:

```typescript
import { UnauthenticatedException } from "@theorchard/backend-ts-pdp-sdk";

try {
  const authorized = await pdpAuthorizationBackend.isAuthorized({
    action: "view",
    resourceId: "123",
    resourceType: "audience",
    resourceGetter: myResourceGetter,
    raiseWhenUnauthorized: false, // Authentication errors still throw!
  });
} catch (error) {
  if (error instanceof UnauthenticatedException) {
    // Handle authentication failure (401) - e.g., refresh token, re-login
    console.error("Authentication failed:", error.message);
  } else {
    // Handle other errors
    console.error("Authorization check failed:", error.message);
  }
}
```

**Impact**: Applications using this SDK must now handle `UnauthenticatedException` explicitly, as it will be thrown even
when `raiseWhenUnauthorized: false` is set. This ensures authentication issues are never silently ignored.

## 2.0.0

### Major Changes

#### BREAKING CHANGE

- PP-1187 Transform list of AllowedTenant objects into an object containing the list, and tenant uuids group by the supported TenantTypes (ParentCompany, CompanyBrand, Account, Subaccount, LabelParticipant).

Before:

The `PPAllowedTenantsDirectiveTransformer` puts a list of `AllowedTenant` objects into the context fields.

After:

The `PPAllowedTenantsDirectiveTransform` puts an `AllowedTenants` object into the context fields. This enables the directive to transform the list of `AllowedTenant` objects into lists of tenant uuids, grouped by tenant type. If you were previously using the list of `AllowedTenant`, this is still available by using `allowedTenants.allowedTenants`. For example:

```typescript
// Before
ownershipNrSoundRecording: async (
        _parent,
        { id },
        { dataSources, fieldPermissions, driver, bookmarkManager }
    ) => {
        const companyBrandTenants = (fieldPermissions?.allowedTenants ?? []) ...
```

becomes:

```typescript
// After
ownershipNrSoundRecording: async (
        _parent,
        { id },
        { dataSources, fieldPermissions, driver, bookmarkManager }
    ) => {
        const companyBrandTenants = (fieldPermissions?.allowedTenants?.allowedTenants ?? []) ...
```

#### Non-breaking change

- Export ppCanPerformDirectiveTransformerFn for easier use by clients

## 1.8.3

### Patch Changes

- PP-1171: Fixes a bug where the caught error was not being logged in GraphqlServerLogger

## 1.8.2

### Patch Changes

- For `PpCanPerformDirectiveTransformer` and`PpCanPerformDirectiveTransformer`,explicitly type `directiveName` property as a `string`, so that it is not interpreted as a string literal type

## 1.8.1

### Patch Changes

- Raise an AuthorizationError from PpCanPerformDirectiveTransformer when the context is invalid

## 1.8.0

### Minor Changes

- PP-1136: Add `PpCanPerformDirectiveTransformer`.

## 1.7.5

### Patch Changes

- PP-1112: Update the `@ppAllowedTenants` directive example in the README.

## 1.7.4

### Patch Changes

- MAINT: Bump ts-jest to get patched versions of brace-expansion and @babel/helpers

## 1.7.3

### Patch Changes

- CRP-29: Export the GetAllowedTenantsUtilsParams type for easier reference from clients of the library

# 1.7.2

### Patch Changes

- PP-1112: Implement `transform` in `PpAllowedTenantsDirectiveTransformer`.

# 1.7.1

### Patch Changes

- PP-1112: Add `ppAllowedTenantsDirectiveTransformerFn` and add the identity_uuid to the `createPermissionsResolver`
  cache key.

# 1.7.0

### Minor Changes

- PP-1112: Implement `createPermissionsResolver` in `PpAllowedTenantsDirectiveTransformer`.

## 1.6.0

### Minor Changes

- PP-1097: Deprecate `PinoLogger` and add `OwsLogger`.

## 1.5.1

### Patch Changes

- PP-1091: README update for ts-pdp-sdk classes and interfaces.

## 1.5.0

### Minor Changes

- PP-1090: Implement `isAuthorizedManyResourcesAndActions` in the `PdpAuthorizationBackend` class.

## 1.4.2

### Patch Changes

- PP-1097: Add Logger classes to `backend-ts-pdp-sdk/index.ts`.

## 1.4.1

### Patch Changes

- PP-1097: Update GraphqlServerLogger documentation.

## 1.4.0

### Minor Changes

- PP-1097: Add PinoLogger and PowerToolsLogger.

Usage:

```typescript
import { createOwsLogger } from "@theorchard/ows-logger";

const pinoLogger = createOwsLogger(opts);
const pdpAuthorizationBackend = new PdpAuthorizationBackend({
  environment: "qa",
  authorizationGetter: exampleAuthorizationGetter,
  logger: new PinoLogger(pinoLogger),
});
```

```typescript
import { Logger } from "@aws-lambda-powertools/logger";

const powerToolsLogger = new Logger({ serviceName: "my-lambda" });
const pdpAuthorizationBackend = new PdpAuthorizationBackend({
  environment: "qa",
  authorizationGetter: exampleAuthorizationGetter,
  logger: new PowerToolsLogger(powerToolsLogger),
});
```

## 1.3.0

### Minor Changes

- PP-1097: Add GraphqlServerLogger.

Usage:

```typescript
import {
  logDebug,
  logError,
  logInfo,
  logWarning,
} from "@theorchard/graphql-server";

const pdpAuthorizationBackend = new PdpAuthorizationBackend({
  environment: "qa",
  authorizationGetter: exampleAuthorizationGetter,
  logger: new GraphqlServerLogger({
    info: logInfo,
    warn: logWarning,
    error: logError,
    debug: logDebug,
  }),
});
```

## 1.2.0

### Minor Changes

- PP-1097: Add Logger interface, ConsoleLogger, and add logger attribute to PdpAuthorizationBackend and OwsPdp.

## 1.1.0

### Minor Changes

- PP-994: Implement pdpAuthorizationBackend.isAuthorizedMany fn

## 1.0.0

### Major Changes

#### Breaking Change

- PP-769 Update constructor for PdpAuthorizationBackend to take the same params as OwsPdpParams and construct the OwsPdp instance directly. Unit tests are updated and enhanced to assert the behavior is correct

Before:

```ts
const owsPdp = new OwsPdp({
  environment: "qa",
  authorizationGetter: exampleAuthorizationGetter,
});
const pdpAuthorizationBackend = new PdpAuthorizationBackend({
  owsPdp,
});
```

After:

```ts
const pdpAuthorizationBackend = new PdpAuthorizationBackend({
  environment: "qa",
  authorizationGetter: exampleAuthorizationGetter,
});
```

## 0.3.18

### Patch Changes

- PP-993: Implement PdpAuthorizationBackend.isAuthorized fxn

## 0.3.17

### Patch Changes

- PP-995 Implement PdpAuthorizationBackend.getAuthorizedTenants

## 0.3.16

### Patch Changes

- PP-991: Implement OwsPdp.checkMyResources fn

## 0.3.15

### Patch Changes

- - PP-992 Implement OwsPdp.getMyAllowedTenants fn

## 0.3.14

### Patch Changes

- Migrate to Biome2

## 0.3.13

### Patch Changes

- PP-992 Fixup configs. This ensures ES2022 is used for building the packages, and that jest recognizes the tsconfig file's settings.

## 0.3.12

### Patch Changes

- PP-986 Export stock resource getters for usage by library users

## 0.3.11

### Patch Changes

- PP-986 Rename ForwardKwargsGetter as PassThroughGetter. This will make it nicer for typescript- folks who don't know kwargs, a very Pythonic concept

## 0.3.10

### Patch Changes

- PP-986 Update the IsAuthorizedParams interface (on AuthorizationBackend interface's isAuthorized fn) so resourceGetter uses the ResourceGetter interface for its type, instead of string. String was just a placeholder until this ticket of work landed

## 0.3.9

### Patch Changes

- PP-987 Stub functions for the OwsPdp connector class. All functions throw a not implemented error, and reference the Jira ticket that will implement the work. Also, add stub jest.fn for the mock OwsPdp connector class.

## 0.3.8

### Patch Changes

- PP-986 Add ResourceGetter interface type; implement ForwardKwargsGetter, MockResourceGetter as they are in python-pdp-sdk

## 0.3.7

### Patch Changes

- MAINT: Refactor reusable mock implementations into **mock** directory with distinct filenames

## 0.3.6

### Patch Changes

- PP-989 Add PdpAuthorizationBackend class. It implements AuthorizationBackend, but for now all the methods throw an exception indicating it is not yet implemented

## 0.3.5

### Patch Changes

- PP-988 Add OwsPdp connector class that uses middleware for authorization header and correlation id

## 0.3.4

### Patch Changes

- PP-989 Introduce CorrelationIdHeaderMiddleware. The OwsPdp connector will use this to ensure the current request's context is used to pass the correlation id to ows-pdp

## 0.3.3

### Patch Changes

- PP-988 Introduce AuthorizationHeaderMiddleware. The OwsPdp connector will use this to ensure the current request's context is used to pass the authorization header jwt to ows-pdp

## 0.3.2

### Patch Changes

- PP-989 Introduce AuthorizationBackend interface and relevant types

## 0.3.1

### Patch Changes

- Ensure the exceptions are exported for use by clients.

## 0.3.0

### Minor Changes

- PP-990 Introduce custom Exception/Error classes

## 0.2.2

### Patch Changes

- Ensure model properties are camelCase and not snake_case

## 0.2.1

### Patch Changes

- Exclude unnecessary models from being auto-generated in backend-ts-pdp-sdk

## 0.2.0

### Minor Changes

- Generate models in backend-ts-pdp-sdk using openapi-generator

## 0.1.1

### Patch Changes

- Update packages to use a biome.json configuration that uses space-indent instead of tab-indent.

## 0.1.0

- Initial commit
