@opentdf/sdk 0.13.0-beta.122 → 0.13.0-beta.124
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/README.md +60 -10
- package/dist/cjs/src/access/access-rpc.js +6 -5
- package/dist/cjs/src/access.js +18 -5
- package/dist/cjs/src/auth/interceptors.js +186 -0
- package/dist/cjs/src/auth/token-providers.js +247 -0
- package/dist/cjs/src/index.js +10 -2
- package/dist/cjs/src/opentdf.js +40 -32
- package/dist/cjs/src/platform.js +3 -46
- package/dist/cjs/src/policy/api.js +9 -5
- package/dist/cjs/src/policy/discovery.js +10 -9
- package/dist/cjs/tdf3/src/client/index.js +35 -17
- package/dist/cjs/tdf3/src/tdf.js +8 -7
- package/dist/types/src/access/access-rpc.d.ts +3 -3
- package/dist/types/src/access/access-rpc.d.ts.map +1 -1
- package/dist/types/src/access.d.ts +3 -3
- package/dist/types/src/access.d.ts.map +1 -1
- package/dist/types/src/auth/interceptors.d.ts +99 -0
- package/dist/types/src/auth/interceptors.d.ts.map +1 -0
- package/dist/types/src/auth/token-providers.d.ts +100 -0
- package/dist/types/src/auth/token-providers.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/opentdf.d.ts +18 -15
- package/dist/types/src/opentdf.d.ts.map +1 -1
- package/dist/types/src/platform.d.ts +6 -3
- package/dist/types/src/platform.d.ts.map +1 -1
- package/dist/types/src/policy/api.d.ts +3 -3
- package/dist/types/src/policy/api.d.ts.map +1 -1
- package/dist/types/src/policy/discovery.d.ts +5 -5
- package/dist/types/src/policy/discovery.d.ts.map +1 -1
- package/dist/types/tdf3/src/client/index.d.ts +10 -1
- package/dist/types/tdf3/src/client/index.d.ts.map +1 -1
- package/dist/types/tdf3/src/tdf.d.ts +5 -2
- package/dist/types/tdf3/src/tdf.d.ts.map +1 -1
- package/dist/web/src/access/access-rpc.js +6 -5
- package/dist/web/src/access.js +18 -5
- package/dist/web/src/auth/interceptors.js +142 -0
- package/dist/web/src/auth/token-providers.js +242 -0
- package/dist/web/src/index.js +3 -1
- package/dist/web/src/opentdf.js +40 -32
- package/dist/web/src/platform.js +3 -46
- package/dist/web/src/policy/api.js +9 -5
- package/dist/web/src/policy/discovery.js +10 -9
- package/dist/web/tdf3/src/client/index.js +35 -17
- package/dist/web/tdf3/src/tdf.js +8 -7
- package/package.json +1 -1
- package/src/access/access-rpc.ts +5 -5
- package/src/access.ts +29 -13
- package/src/auth/interceptors.ts +197 -0
- package/src/auth/token-providers.ts +303 -0
- package/src/index.ts +18 -0
- package/src/opentdf.ts +54 -34
- package/src/platform.ts +8 -52
- package/src/policy/api.ts +8 -5
- package/src/policy/discovery.ts +9 -9
- package/tdf3/src/client/index.ts +46 -17
- package/tdf3/src/tdf.ts +14 -11
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { type Interceptor } from '@connectrpc/connect';
|
|
2
|
+
export type { Interceptor } from '@connectrpc/connect';
|
|
3
|
+
import { type CryptoService, type KeyPair } from '../../tdf3/src/crypto/declarations.js';
|
|
4
|
+
import * as DefaultCryptoService from '../../tdf3/src/crypto/index.js';
|
|
5
|
+
import DPoP from './dpop.js';
|
|
6
|
+
import { type AuthProvider } from './auth.js';
|
|
7
|
+
import { base64 } from '../encodings/index.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A function that returns a valid access token string.
|
|
11
|
+
* Called per-request; implementations should handle caching/refresh internally.
|
|
12
|
+
*/
|
|
13
|
+
export type TokenProvider = () => Promise<string>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Options for creating a DPoP-aware auth interceptor.
|
|
17
|
+
*/
|
|
18
|
+
export type DPoPInterceptorOptions = {
|
|
19
|
+
/** Function that returns a valid access token (may cache/refresh internally). */
|
|
20
|
+
tokenProvider: TokenProvider;
|
|
21
|
+
/** DPoP signing key pair. If omitted, one is generated automatically. */
|
|
22
|
+
dpopKeys?: KeyPair | Promise<KeyPair>;
|
|
23
|
+
/** CryptoService for signing. Defaults to DefaultCryptoService. */
|
|
24
|
+
cryptoService?: CryptoService;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A DPoP interceptor that also exposes the resolved signing key pair.
|
|
29
|
+
* TDF encrypt/decrypt needs these keys for request body signing (reqSignature).
|
|
30
|
+
*/
|
|
31
|
+
export type DPoPInterceptor = Interceptor & {
|
|
32
|
+
/** The resolved DPoP key pair, for use in TDF request token signing. */
|
|
33
|
+
readonly dpopKeys: Promise<KeyPair>;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Creates a simple bearer-token interceptor.
|
|
38
|
+
* Calls `tokenProvider()` per-request and sets the `Authorization` header.
|
|
39
|
+
*
|
|
40
|
+
* @param tokenProvider Function returning a valid access token.
|
|
41
|
+
* @returns A Connect RPC Interceptor.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* const opentdf = new OpenTDF({
|
|
46
|
+
* interceptors: [authTokenInterceptor(() => myAuth.getAccessToken())],
|
|
47
|
+
* platformUrl: '/api',
|
|
48
|
+
* });
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export function authTokenInterceptor(tokenProvider: TokenProvider): Interceptor {
|
|
52
|
+
return (next) => async (req) => {
|
|
53
|
+
const token = await tokenProvider();
|
|
54
|
+
req.header.set('Authorization', `Bearer ${token}`);
|
|
55
|
+
return next(req);
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Creates a DPoP-aware auth interceptor.
|
|
61
|
+
* Per-request: gets token, generates DPoP proof JWT, sets Authorization + DPoP + X-VirtruPubKey headers.
|
|
62
|
+
* Exposes `dpopKeys` for TDF request body signing.
|
|
63
|
+
*
|
|
64
|
+
* @param options DPoP interceptor configuration.
|
|
65
|
+
* @returns A DPoP interceptor with an exposed `dpopKeys` promise.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* const dpopInterceptor = authTokenDPoPInterceptor({
|
|
70
|
+
* tokenProvider: () => myAuth.getAccessToken(),
|
|
71
|
+
* });
|
|
72
|
+
* const opentdf = new OpenTDF({
|
|
73
|
+
* interceptors: [dpopInterceptor],
|
|
74
|
+
* dpopKeys: dpopInterceptor.dpopKeys,
|
|
75
|
+
* platformUrl: '/api',
|
|
76
|
+
* });
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export function authTokenDPoPInterceptor(options: DPoPInterceptorOptions): DPoPInterceptor {
|
|
80
|
+
const cryptoService = options.cryptoService ?? DefaultCryptoService;
|
|
81
|
+
const dpopKeysPromise: Promise<KeyPair> = options.dpopKeys
|
|
82
|
+
? Promise.resolve(options.dpopKeys)
|
|
83
|
+
: cryptoService.generateSigningKeyPair();
|
|
84
|
+
|
|
85
|
+
const interceptor: Interceptor = (next) => async (req) => {
|
|
86
|
+
const [token, keys] = await Promise.all([options.tokenProvider(), dpopKeysPromise]);
|
|
87
|
+
|
|
88
|
+
const url = new URL(req.url);
|
|
89
|
+
const httpUri = `${url.origin}${url.pathname}`;
|
|
90
|
+
|
|
91
|
+
// Generate DPoP proof JWT for this request
|
|
92
|
+
const dpopProof = await DPoP(keys, cryptoService, httpUri, 'POST');
|
|
93
|
+
|
|
94
|
+
// Export public key PEM for X-VirtruPubKey header
|
|
95
|
+
const publicKeyPem = await cryptoService.exportPublicKeyPem(keys.publicKey);
|
|
96
|
+
|
|
97
|
+
req.header.set('Authorization', `Bearer ${token}`);
|
|
98
|
+
req.header.set('DPoP', dpopProof);
|
|
99
|
+
req.header.set('X-VirtruPubKey', base64.encode(publicKeyPem));
|
|
100
|
+
|
|
101
|
+
return next(req);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// Attach dpopKeys to the interceptor function
|
|
105
|
+
const dpopInterceptor = interceptor as DPoPInterceptor;
|
|
106
|
+
Object.defineProperty(dpopInterceptor, 'dpopKeys', {
|
|
107
|
+
value: dpopKeysPromise,
|
|
108
|
+
writable: false,
|
|
109
|
+
enumerable: true,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
return dpopInterceptor;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Creates an interceptor that bridges an existing AuthProvider to the Interceptor pattern.
|
|
117
|
+
* Use this for backwards compatibility when migrating from AuthProvider to interceptors.
|
|
118
|
+
*
|
|
119
|
+
* @param authProvider The legacy AuthProvider to bridge.
|
|
120
|
+
* @returns A Connect RPC Interceptor.
|
|
121
|
+
*/
|
|
122
|
+
export function authProviderInterceptor(authProvider: AuthProvider): Interceptor {
|
|
123
|
+
return (next) => async (req) => {
|
|
124
|
+
const url = new URL(req.url);
|
|
125
|
+
const pathOnly = url.pathname;
|
|
126
|
+
// Signs only the path of the url in the request
|
|
127
|
+
let token;
|
|
128
|
+
try {
|
|
129
|
+
token = await authProvider.withCreds({
|
|
130
|
+
url: pathOnly,
|
|
131
|
+
method: 'POST',
|
|
132
|
+
// Start with any headers Connect already has
|
|
133
|
+
headers: {
|
|
134
|
+
...Object.fromEntries(req.header.entries()),
|
|
135
|
+
'Content-Type': 'application/json',
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
} catch (err) {
|
|
139
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
140
|
+
if (msg.includes('public key') || msg.includes('updateClientPublicKey')) {
|
|
141
|
+
throw new Error(
|
|
142
|
+
'PlatformClient: DPoP key binding is not complete. ' +
|
|
143
|
+
'If you are using OpenTDF with PlatformClient, create OpenTDF first and ' +
|
|
144
|
+
'`await client.ready` before constructing PlatformClient. ' +
|
|
145
|
+
`Original error: ${msg}`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
Object.entries(token.headers).forEach(([key, value]) => {
|
|
152
|
+
req.header.set(key, value);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
return await next(req);
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Auth configuration: either a legacy AuthProvider or an object with interceptors.
|
|
161
|
+
*/
|
|
162
|
+
export type AuthConfig = AuthProvider | { interceptors: Interceptor[] };
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Type guard for AuthConfig with interceptors.
|
|
166
|
+
*/
|
|
167
|
+
export function isInterceptorConfig(auth: AuthConfig): auth is { interceptors: Interceptor[] } {
|
|
168
|
+
return 'interceptors' in auth && Array.isArray((auth as { interceptors: unknown }).interceptors);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Resolves an AuthConfig into interceptors for use with PlatformClient.
|
|
173
|
+
* If the config is an AuthProvider, it is bridged via authProviderInterceptor.
|
|
174
|
+
*/
|
|
175
|
+
export function resolveInterceptors(auth: AuthConfig): Interceptor[] {
|
|
176
|
+
if (isInterceptorConfig(auth)) {
|
|
177
|
+
return auth.interceptors;
|
|
178
|
+
}
|
|
179
|
+
return [authProviderInterceptor(auth)];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Resolves an AuthConfig into both interceptors and an optional AuthProvider.
|
|
184
|
+
* The AuthProvider is available for legacy code paths that need withCreds().
|
|
185
|
+
*/
|
|
186
|
+
export function resolveAuthConfig(auth: AuthConfig): {
|
|
187
|
+
interceptors: Interceptor[];
|
|
188
|
+
authProvider?: AuthProvider;
|
|
189
|
+
} {
|
|
190
|
+
if (isInterceptorConfig(auth)) {
|
|
191
|
+
return { interceptors: auth.interceptors };
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
interceptors: [authProviderInterceptor(auth)],
|
|
195
|
+
authProvider: auth,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { type TokenProvider } from './interceptors.js';
|
|
2
|
+
import { ConfigurationError, TdfError } from '../errors.js';
|
|
3
|
+
import { rstrip } from '../utils.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Options for client credentials token provider.
|
|
7
|
+
*
|
|
8
|
+
* **Not for browser use.** Client secrets must not be exposed in client-side code.
|
|
9
|
+
* Use this only in server-side (Node.js/Deno) environments.
|
|
10
|
+
*/
|
|
11
|
+
export type ClientCredentialsTokenProviderOptions = {
|
|
12
|
+
/** OIDC client ID. */
|
|
13
|
+
clientId: string;
|
|
14
|
+
/** OIDC client secret. */
|
|
15
|
+
clientSecret: string;
|
|
16
|
+
/** OIDC IdP origin, e.g. 'http://localhost:8080/auth/realms/opentdf'. */
|
|
17
|
+
oidcOrigin: string;
|
|
18
|
+
/** Override the token endpoint (defaults to `${oidcOrigin}/protocol/openid-connect/token`). */
|
|
19
|
+
oidcTokenEndpoint?: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Options for refresh token provider.
|
|
24
|
+
*/
|
|
25
|
+
export type RefreshTokenProviderOptions = {
|
|
26
|
+
/** OIDC client ID. */
|
|
27
|
+
clientId: string;
|
|
28
|
+
/** Refresh token obtained from a prior login flow. */
|
|
29
|
+
refreshToken: string;
|
|
30
|
+
/** OIDC IdP origin, e.g. 'http://localhost:8080/auth/realms/opentdf'. */
|
|
31
|
+
oidcOrigin: string;
|
|
32
|
+
/** Override the token endpoint. */
|
|
33
|
+
oidcTokenEndpoint?: string;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Options for external JWT token provider (RFC 8693 token exchange).
|
|
38
|
+
*/
|
|
39
|
+
export type ExternalJwtTokenProviderOptions = {
|
|
40
|
+
/** OIDC client ID. */
|
|
41
|
+
clientId: string;
|
|
42
|
+
/** External JWT to exchange. */
|
|
43
|
+
externalJwt: string;
|
|
44
|
+
/** OIDC IdP origin, e.g. 'http://localhost:8080/auth/realms/opentdf'. */
|
|
45
|
+
oidcOrigin: string;
|
|
46
|
+
/** Override the token endpoint. */
|
|
47
|
+
oidcTokenEndpoint?: string;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
type TokenResponse = {
|
|
51
|
+
access_token: string;
|
|
52
|
+
refresh_token?: string;
|
|
53
|
+
expires_in?: number;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function resolveTokenEndpoint(oidcOrigin: string, override?: string): string {
|
|
57
|
+
if (override?.trim()) return override;
|
|
58
|
+
const base = oidcOrigin?.trim();
|
|
59
|
+
if (!base) {
|
|
60
|
+
throw new ConfigurationError('oidcOrigin or oidcTokenEndpoint is required');
|
|
61
|
+
}
|
|
62
|
+
return `${rstrip(base, '/')}/protocol/openid-connect/token`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Decode a JWT's exp claim without verifying the signature.
|
|
67
|
+
* Returns the expiration time in seconds since epoch, or undefined if not present.
|
|
68
|
+
*/
|
|
69
|
+
function getJwtExpiration(token: string): number | undefined {
|
|
70
|
+
try {
|
|
71
|
+
const parts = token.split('.');
|
|
72
|
+
if (parts.length !== 3) return undefined;
|
|
73
|
+
// Base64url decode the payload
|
|
74
|
+
const payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
75
|
+
const padded = payload + '='.repeat((4 - (payload.length % 4)) % 4);
|
|
76
|
+
const decoded = JSON.parse(atob(padded));
|
|
77
|
+
return typeof decoded.exp === 'number' ? decoded.exp : undefined;
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Compute the absolute expiry (seconds since epoch) for a token response.
|
|
85
|
+
* Prefers `expires_in` from the token response, falls back to the JWT `exp` claim.
|
|
86
|
+
*/
|
|
87
|
+
function resolveTokenExpiry(accessToken: string, expiresIn?: number): number | undefined {
|
|
88
|
+
if (typeof expiresIn === 'number') {
|
|
89
|
+
return Date.now() / 1000 + expiresIn;
|
|
90
|
+
}
|
|
91
|
+
return getJwtExpiration(accessToken);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isTokenExpired(expiry: number | undefined, bufferSeconds = 30): boolean {
|
|
95
|
+
if (expiry === undefined) return true;
|
|
96
|
+
return Date.now() / 1000 >= expiry - bufferSeconds;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function fetchToken(
|
|
100
|
+
tokenEndpoint: string,
|
|
101
|
+
body: Record<string, string>
|
|
102
|
+
): Promise<TokenResponse> {
|
|
103
|
+
const response = await fetch(tokenEndpoint, {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
headers: {
|
|
106
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
107
|
+
Accept: 'application/json',
|
|
108
|
+
},
|
|
109
|
+
body: new URLSearchParams(body).toString(),
|
|
110
|
+
});
|
|
111
|
+
if (!response.ok) {
|
|
112
|
+
const text = await response.text();
|
|
113
|
+
throw new TdfError(
|
|
114
|
+
`Token request failed: POST [${tokenEndpoint}] => ${response.status} ${response.statusText}: ${text}`
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
return (await response.json()) as TokenResponse;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Creates a TokenProvider that obtains tokens via the OAuth2 client credentials grant.
|
|
122
|
+
* Tokens are cached and automatically refreshed when expired.
|
|
123
|
+
*
|
|
124
|
+
* **Not for browser use.** Client secrets must not be exposed in client-side code.
|
|
125
|
+
* Use this only in server-side (Node.js/Deno) environments.
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* const client = new OpenTDF({
|
|
130
|
+
* interceptors: [authTokenInterceptor(clientCredentialsTokenProvider({
|
|
131
|
+
* clientId: 'opentdf',
|
|
132
|
+
* clientSecret: 'secret',
|
|
133
|
+
* oidcOrigin: 'http://localhost:8080/auth/realms/opentdf',
|
|
134
|
+
* }))],
|
|
135
|
+
* platformUrl: 'http://localhost:8080',
|
|
136
|
+
* });
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
export function clientCredentialsTokenProvider(
|
|
140
|
+
options: ClientCredentialsTokenProviderOptions
|
|
141
|
+
): TokenProvider {
|
|
142
|
+
if (!options.clientId || !options.clientSecret) {
|
|
143
|
+
throw new ConfigurationError('clientId and clientSecret are required');
|
|
144
|
+
}
|
|
145
|
+
const tokenEndpoint = resolveTokenEndpoint(options.oidcOrigin, options.oidcTokenEndpoint);
|
|
146
|
+
let cachedToken: string | undefined;
|
|
147
|
+
let cachedExpiry: number | undefined;
|
|
148
|
+
let inFlight: Promise<string> | undefined;
|
|
149
|
+
|
|
150
|
+
return async () => {
|
|
151
|
+
if (cachedToken && !isTokenExpired(cachedExpiry)) {
|
|
152
|
+
return cachedToken;
|
|
153
|
+
}
|
|
154
|
+
if (!inFlight) {
|
|
155
|
+
inFlight = (async () => {
|
|
156
|
+
try {
|
|
157
|
+
const resp = await fetchToken(tokenEndpoint, {
|
|
158
|
+
grant_type: 'client_credentials',
|
|
159
|
+
client_id: options.clientId,
|
|
160
|
+
client_secret: options.clientSecret,
|
|
161
|
+
});
|
|
162
|
+
cachedToken = resp.access_token;
|
|
163
|
+
cachedExpiry = resolveTokenExpiry(resp.access_token, resp.expires_in);
|
|
164
|
+
return cachedToken;
|
|
165
|
+
} finally {
|
|
166
|
+
inFlight = undefined;
|
|
167
|
+
}
|
|
168
|
+
})();
|
|
169
|
+
}
|
|
170
|
+
return inFlight;
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Creates a TokenProvider that uses a refresh token to obtain access tokens.
|
|
176
|
+
* On the first call, exchanges the refresh token. Subsequent calls use the
|
|
177
|
+
* latest refresh token from the IdP response.
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```ts
|
|
181
|
+
* const client = new OpenTDF({
|
|
182
|
+
* interceptors: [authTokenInterceptor(refreshTokenProvider({
|
|
183
|
+
* clientId: 'my-app',
|
|
184
|
+
* refreshToken: 'refresh-token-from-login',
|
|
185
|
+
* oidcOrigin: 'http://localhost:8080/auth/realms/opentdf',
|
|
186
|
+
* }))],
|
|
187
|
+
* platformUrl: 'http://localhost:8080',
|
|
188
|
+
* });
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
export function refreshTokenProvider(options: RefreshTokenProviderOptions): TokenProvider {
|
|
192
|
+
if (!options.clientId || !options.refreshToken) {
|
|
193
|
+
throw new ConfigurationError('clientId and refreshToken are required');
|
|
194
|
+
}
|
|
195
|
+
const tokenEndpoint = resolveTokenEndpoint(options.oidcOrigin, options.oidcTokenEndpoint);
|
|
196
|
+
let currentRefreshToken = options.refreshToken;
|
|
197
|
+
let cachedToken: string | undefined;
|
|
198
|
+
let cachedExpiry: number | undefined;
|
|
199
|
+
let inFlight: Promise<string> | undefined;
|
|
200
|
+
|
|
201
|
+
return async () => {
|
|
202
|
+
if (cachedToken && !isTokenExpired(cachedExpiry)) {
|
|
203
|
+
return cachedToken;
|
|
204
|
+
}
|
|
205
|
+
if (!inFlight) {
|
|
206
|
+
inFlight = (async () => {
|
|
207
|
+
try {
|
|
208
|
+
const resp = await fetchToken(tokenEndpoint, {
|
|
209
|
+
grant_type: 'refresh_token',
|
|
210
|
+
refresh_token: currentRefreshToken,
|
|
211
|
+
client_id: options.clientId,
|
|
212
|
+
});
|
|
213
|
+
cachedToken = resp.access_token;
|
|
214
|
+
cachedExpiry = resolveTokenExpiry(resp.access_token, resp.expires_in);
|
|
215
|
+
if (resp.refresh_token) {
|
|
216
|
+
currentRefreshToken = resp.refresh_token;
|
|
217
|
+
}
|
|
218
|
+
return cachedToken;
|
|
219
|
+
} finally {
|
|
220
|
+
inFlight = undefined;
|
|
221
|
+
}
|
|
222
|
+
})();
|
|
223
|
+
}
|
|
224
|
+
return inFlight;
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Creates a TokenProvider that exchanges an external JWT for a platform token
|
|
230
|
+
* via RFC 8693 token exchange. After the initial exchange, uses the refresh
|
|
231
|
+
* token for subsequent calls.
|
|
232
|
+
*
|
|
233
|
+
* @example
|
|
234
|
+
* ```ts
|
|
235
|
+
* const client = new OpenTDF({
|
|
236
|
+
* interceptors: [authTokenInterceptor(externalJwtTokenProvider({
|
|
237
|
+
* clientId: 'my-app',
|
|
238
|
+
* externalJwt: 'eyJhbGciOi...',
|
|
239
|
+
* oidcOrigin: 'http://localhost:8080/auth/realms/opentdf',
|
|
240
|
+
* }))],
|
|
241
|
+
* platformUrl: 'http://localhost:8080',
|
|
242
|
+
* });
|
|
243
|
+
* ```
|
|
244
|
+
*/
|
|
245
|
+
export function externalJwtTokenProvider(options: ExternalJwtTokenProviderOptions): TokenProvider {
|
|
246
|
+
if (!options.clientId || !options.externalJwt) {
|
|
247
|
+
throw new ConfigurationError('clientId and externalJwt are required');
|
|
248
|
+
}
|
|
249
|
+
const tokenEndpoint = resolveTokenEndpoint(options.oidcOrigin, options.oidcTokenEndpoint);
|
|
250
|
+
let cachedToken: string | undefined;
|
|
251
|
+
let cachedExpiry: number | undefined;
|
|
252
|
+
let currentRefreshToken: string | undefined;
|
|
253
|
+
let initialExchangeDone = false;
|
|
254
|
+
let inFlight: Promise<string> | undefined;
|
|
255
|
+
|
|
256
|
+
return async () => {
|
|
257
|
+
if (cachedToken && !isTokenExpired(cachedExpiry)) {
|
|
258
|
+
return cachedToken;
|
|
259
|
+
}
|
|
260
|
+
if (!inFlight) {
|
|
261
|
+
inFlight = (async () => {
|
|
262
|
+
try {
|
|
263
|
+
let resp: TokenResponse;
|
|
264
|
+
if (!initialExchangeDone) {
|
|
265
|
+
resp = await fetchToken(tokenEndpoint, {
|
|
266
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
|
|
267
|
+
subject_token: options.externalJwt,
|
|
268
|
+
subject_token_type: 'urn:ietf:params:oauth:token-type:jwt',
|
|
269
|
+
audience: options.clientId,
|
|
270
|
+
client_id: options.clientId,
|
|
271
|
+
});
|
|
272
|
+
initialExchangeDone = true;
|
|
273
|
+
} else if (currentRefreshToken) {
|
|
274
|
+
resp = await fetchToken(tokenEndpoint, {
|
|
275
|
+
grant_type: 'refresh_token',
|
|
276
|
+
refresh_token: currentRefreshToken,
|
|
277
|
+
client_id: options.clientId,
|
|
278
|
+
});
|
|
279
|
+
} else {
|
|
280
|
+
// Re-exchange the original JWT if no refresh token available
|
|
281
|
+
resp = await fetchToken(tokenEndpoint, {
|
|
282
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
|
|
283
|
+
subject_token: options.externalJwt,
|
|
284
|
+
subject_token_type: 'urn:ietf:params:oauth:token-type:jwt',
|
|
285
|
+
audience: options.clientId,
|
|
286
|
+
client_id: options.clientId,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
cachedToken = resp.access_token;
|
|
291
|
+
cachedExpiry = resolveTokenExpiry(resp.access_token, resp.expires_in);
|
|
292
|
+
if (resp.refresh_token) {
|
|
293
|
+
currentRefreshToken = resp.refresh_token;
|
|
294
|
+
}
|
|
295
|
+
return cachedToken;
|
|
296
|
+
} finally {
|
|
297
|
+
inFlight = undefined;
|
|
298
|
+
}
|
|
299
|
+
})();
|
|
300
|
+
}
|
|
301
|
+
return inFlight;
|
|
302
|
+
};
|
|
303
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
export { type AuthProvider, type HttpMethod, HttpRequest, withHeaders } from './auth/auth.js';
|
|
2
2
|
export * as AuthProviders from './auth/providers.js';
|
|
3
|
+
export {
|
|
4
|
+
authTokenInterceptor,
|
|
5
|
+
authTokenDPoPInterceptor,
|
|
6
|
+
authProviderInterceptor,
|
|
7
|
+
type AuthConfig,
|
|
8
|
+
type DPoPInterceptor,
|
|
9
|
+
type DPoPInterceptorOptions,
|
|
10
|
+
type Interceptor,
|
|
11
|
+
type TokenProvider,
|
|
12
|
+
} from './auth/interceptors.js';
|
|
13
|
+
export {
|
|
14
|
+
clientCredentialsTokenProvider,
|
|
15
|
+
refreshTokenProvider,
|
|
16
|
+
externalJwtTokenProvider,
|
|
17
|
+
type ClientCredentialsTokenProviderOptions,
|
|
18
|
+
type RefreshTokenProviderOptions,
|
|
19
|
+
type ExternalJwtTokenProviderOptions,
|
|
20
|
+
} from './auth/token-providers.js';
|
|
3
21
|
export { attributeFQNsAsValues } from './policy/api.js';
|
|
4
22
|
export {
|
|
5
23
|
listAttributes,
|
package/src/opentdf.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type AuthProvider } from './auth/providers.js';
|
|
2
|
+
import { type Interceptor } from '@connectrpc/connect';
|
|
2
3
|
import { ConfigurationError, InvalidFileError } from './errors.js';
|
|
3
4
|
export { Client as TDF3Client } from '../tdf3/src/client/index.js';
|
|
4
5
|
import { Chunker, fromSource, sourceToStream, type Source } from './seekable.js';
|
|
@@ -164,8 +165,17 @@ export type OpenTDFOptions = {
|
|
|
164
165
|
/** Platform URL. */
|
|
165
166
|
platformUrl?: string;
|
|
166
167
|
|
|
167
|
-
/**
|
|
168
|
-
|
|
168
|
+
/**
|
|
169
|
+
* Connect RPC interceptors for authentication. Preferred over authProvider.
|
|
170
|
+
* Use `authTokenInterceptor()` or `authTokenDPoPInterceptor()` to create interceptors.
|
|
171
|
+
*/
|
|
172
|
+
interceptors?: Interceptor[];
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Auth provider for connections to the policy service and KASes.
|
|
176
|
+
* @deprecated since 0.14.0. Use `interceptors` with `authTokenInterceptor()` or `authTokenDPoPInterceptor()` instead.
|
|
177
|
+
*/
|
|
178
|
+
authProvider?: AuthProvider;
|
|
169
179
|
|
|
170
180
|
/** Default settings for 'encrypt' type requests. */
|
|
171
181
|
defaultCreateOptions?: Omit<CreateOptions, 'source'>;
|
|
@@ -236,18 +246,10 @@ export type TDFReader = {
|
|
|
236
246
|
* It also requires a platform URL to be set, which is used to fetch key access servers and policies.
|
|
237
247
|
* @example
|
|
238
248
|
* ```
|
|
239
|
-
* import {
|
|
240
|
-
*
|
|
241
|
-
* const oidcCredentials: RefreshTokenCredentials = {
|
|
242
|
-
* clientId: keycloakClientId,
|
|
243
|
-
* exchange: 'refresh',
|
|
244
|
-
* refreshToken: refreshToken,
|
|
245
|
-
* oidcOrigin: keycloakUrl,
|
|
246
|
-
* };
|
|
247
|
-
* const authProvider = await AuthProviders.refreshAuthProvider(oidcCredentials);
|
|
249
|
+
* import { authTokenInterceptor, OpenTDF } from '@opentdf/sdk';
|
|
248
250
|
*
|
|
249
251
|
* const client = new OpenTDF({
|
|
250
|
-
*
|
|
252
|
+
* interceptors: [authTokenInterceptor(() => `${myAuth.token.accessToken}`)],
|
|
251
253
|
* platformUrl: 'https://platform.example.com',
|
|
252
254
|
* });
|
|
253
255
|
*
|
|
@@ -264,8 +266,10 @@ export class OpenTDF {
|
|
|
264
266
|
readonly platformUrl: string;
|
|
265
267
|
/** The policy service endpoint */
|
|
266
268
|
readonly policyEndpoint: string;
|
|
267
|
-
/** The auth provider for the OpenTDF instance. */
|
|
268
|
-
readonly authProvider
|
|
269
|
+
/** The auth provider for the OpenTDF instance (deprecated, use interceptors). */
|
|
270
|
+
readonly authProvider?: AuthProvider;
|
|
271
|
+
/** Connect RPC interceptors for authentication. */
|
|
272
|
+
readonly interceptors?: Interceptor[];
|
|
269
273
|
/** If DPoP is enabled for this instance. */
|
|
270
274
|
readonly dpopEnabled: boolean;
|
|
271
275
|
/** Default options for creating TDF objects. */
|
|
@@ -283,6 +287,7 @@ export class OpenTDF {
|
|
|
283
287
|
|
|
284
288
|
constructor({
|
|
285
289
|
authProvider,
|
|
290
|
+
interceptors,
|
|
286
291
|
dpopKeys,
|
|
287
292
|
defaultCreateOptions,
|
|
288
293
|
defaultReadOptions,
|
|
@@ -291,7 +296,11 @@ export class OpenTDF {
|
|
|
291
296
|
platformUrl,
|
|
292
297
|
cryptoService,
|
|
293
298
|
}: OpenTDFOptions) {
|
|
299
|
+
if (!authProvider && !interceptors?.length) {
|
|
300
|
+
throw new ConfigurationError('Either authProvider or interceptors must be provided.');
|
|
301
|
+
}
|
|
294
302
|
this.authProvider = authProvider;
|
|
303
|
+
this.interceptors = interceptors;
|
|
295
304
|
this.defaultCreateOptions = defaultCreateOptions || {};
|
|
296
305
|
this.defaultReadOptions = defaultReadOptions || {};
|
|
297
306
|
this.dpopEnabled = !disableDPoP;
|
|
@@ -308,6 +317,7 @@ export class OpenTDF {
|
|
|
308
317
|
this.dpopKeys = dpopKeys ?? this.cryptoService.generateSigningKeyPair();
|
|
309
318
|
this.tdf3Client = new TDF3Client({
|
|
310
319
|
authProvider,
|
|
320
|
+
interceptors,
|
|
311
321
|
dpopEnabled: this.dpopEnabled,
|
|
312
322
|
dpopKeys: this.dpopEnabled ? this.dpopKeys : undefined,
|
|
313
323
|
kasEndpoint: this.platformUrl || 'https://disallow.all.invalid',
|
|
@@ -315,21 +325,31 @@ export class OpenTDF {
|
|
|
315
325
|
policyEndpoint,
|
|
316
326
|
cryptoService: this.cryptoService,
|
|
317
327
|
});
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
328
|
+
|
|
329
|
+
if (interceptors?.length && !authProvider) {
|
|
330
|
+
// Interceptor path: no updateClientPublicKey needed.
|
|
331
|
+
// DPoP key binding is handled by the interceptor itself.
|
|
332
|
+
this.ready = Promise.resolve();
|
|
333
|
+
} else if (authProvider) {
|
|
334
|
+
// Legacy AuthProvider path: eagerly bind DPoP keys to the auth provider
|
|
335
|
+
// so PlatformClient can make gRPC calls without waiting for a TDF
|
|
336
|
+
// operation first.
|
|
337
|
+
// Note: TDF3Client.createSessionKeys() also calls updateClientPublicKey
|
|
338
|
+
// with the same keys, but the duplicate call is benign —
|
|
339
|
+
// refreshTokenClaimsWithClientPubkeyIfNeeded short-circuits when
|
|
340
|
+
// the signing key hasn't changed.
|
|
341
|
+
this.ready = this.dpopEnabled
|
|
342
|
+
? this.dpopKeys.then((keys) => authProvider.updateClientPublicKey(keys))
|
|
343
|
+
: Promise.resolve();
|
|
344
|
+
// Prevent unhandled rejection if caller doesn't await ready.
|
|
345
|
+
// The error will still surface via TDF3Client's own key binding
|
|
346
|
+
// when encrypt/decrypt is called.
|
|
347
|
+
this.ready.catch((err) => {
|
|
348
|
+
console.warn('OpenTDF: DPoP key binding failed during initialization:', err);
|
|
349
|
+
});
|
|
350
|
+
} else {
|
|
351
|
+
this.ready = Promise.resolve();
|
|
352
|
+
}
|
|
333
353
|
}
|
|
334
354
|
|
|
335
355
|
/** Creates a new TDF stream. */
|
|
@@ -485,9 +505,9 @@ class ZTDFReader {
|
|
|
485
505
|
|
|
486
506
|
const dpopKeys = await this.client.dpopKeys;
|
|
487
507
|
|
|
488
|
-
const {
|
|
489
|
-
if (!
|
|
490
|
-
throw new ConfigurationError('authProvider
|
|
508
|
+
const { auth, cryptoService } = this.client;
|
|
509
|
+
if (!auth) {
|
|
510
|
+
throw new ConfigurationError('authProvider or interceptors are required');
|
|
491
511
|
}
|
|
492
512
|
|
|
493
513
|
let allowList: OriginAllowList | undefined;
|
|
@@ -498,14 +518,14 @@ class ZTDFReader {
|
|
|
498
518
|
this.opts.ignoreAllowlist
|
|
499
519
|
);
|
|
500
520
|
} else if (this.opts.platformUrl) {
|
|
501
|
-
allowList = await fetchKeyAccessServers(this.opts.platformUrl,
|
|
521
|
+
allowList = await fetchKeyAccessServers(this.opts.platformUrl, auth);
|
|
502
522
|
}
|
|
503
523
|
|
|
504
524
|
const overview = await this.overview;
|
|
505
525
|
const oldStream = await decryptStreamFrom(
|
|
506
526
|
{
|
|
507
527
|
allowList,
|
|
508
|
-
|
|
528
|
+
auth,
|
|
509
529
|
chunker: this.source,
|
|
510
530
|
concurrencyLimit: 1,
|
|
511
531
|
cryptoService,
|