@opentdf/sdk 0.12.0 → 0.13.0-beta.122

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.
Files changed (48) hide show
  1. package/dist/cjs/src/auth/dpop.js +4 -4
  2. package/dist/cjs/src/auth/oidc.js +5 -3
  3. package/dist/cjs/src/version.js +1 -1
  4. package/dist/cjs/tdf3/src/crypto/core/ec.js +88 -0
  5. package/dist/cjs/tdf3/src/crypto/core/key-format.js +359 -0
  6. package/dist/cjs/tdf3/src/crypto/core/keys.js +85 -0
  7. package/dist/cjs/tdf3/src/crypto/core/rsa.js +120 -0
  8. package/dist/cjs/tdf3/src/crypto/core/signing.js +178 -0
  9. package/dist/cjs/tdf3/src/crypto/core/symmetric.js +205 -0
  10. package/dist/cjs/tdf3/src/crypto/index.js +69 -1051
  11. package/dist/types/src/auth/oidc.d.ts +1 -1
  12. package/dist/types/src/auth/oidc.d.ts.map +1 -1
  13. package/dist/types/src/version.d.ts +1 -1
  14. package/dist/types/tdf3/src/crypto/core/ec.d.ts +11 -0
  15. package/dist/types/tdf3/src/crypto/core/ec.d.ts.map +1 -0
  16. package/dist/types/tdf3/src/crypto/core/key-format.d.ts +41 -0
  17. package/dist/types/tdf3/src/crypto/core/key-format.d.ts.map +1 -0
  18. package/dist/types/tdf3/src/crypto/core/keys.d.ts +27 -0
  19. package/dist/types/tdf3/src/crypto/core/keys.d.ts.map +1 -0
  20. package/dist/types/tdf3/src/crypto/core/rsa.d.ts +35 -0
  21. package/dist/types/tdf3/src/crypto/core/rsa.d.ts.map +1 -0
  22. package/dist/types/tdf3/src/crypto/core/signing.d.ts +10 -0
  23. package/dist/types/tdf3/src/crypto/core/signing.d.ts.map +1 -0
  24. package/dist/types/tdf3/src/crypto/core/symmetric.d.ts +68 -0
  25. package/dist/types/tdf3/src/crypto/core/symmetric.d.ts.map +1 -0
  26. package/dist/types/tdf3/src/crypto/index.d.ts +11 -164
  27. package/dist/types/tdf3/src/crypto/index.d.ts.map +1 -1
  28. package/dist/web/src/auth/dpop.js +4 -4
  29. package/dist/web/src/auth/oidc.js +5 -3
  30. package/dist/web/src/version.js +1 -1
  31. package/dist/web/tdf3/src/crypto/core/ec.js +84 -0
  32. package/dist/web/tdf3/src/crypto/core/key-format.js +348 -0
  33. package/dist/web/tdf3/src/crypto/core/keys.js +78 -0
  34. package/dist/web/tdf3/src/crypto/core/rsa.js +112 -0
  35. package/dist/web/tdf3/src/crypto/core/signing.js +174 -0
  36. package/dist/web/tdf3/src/crypto/core/symmetric.js +192 -0
  37. package/dist/web/tdf3/src/crypto/index.js +13 -994
  38. package/package.json +1 -1
  39. package/src/auth/dpop.ts +3 -3
  40. package/src/auth/oidc.ts +5 -3
  41. package/src/version.ts +1 -1
  42. package/tdf3/src/crypto/core/ec.ts +118 -0
  43. package/tdf3/src/crypto/core/key-format.ts +420 -0
  44. package/tdf3/src/crypto/core/keys.ts +86 -0
  45. package/tdf3/src/crypto/core/rsa.ts +144 -0
  46. package/tdf3/src/crypto/core/signing.ts +214 -0
  47. package/tdf3/src/crypto/core/symmetric.ts +265 -0
  48. package/tdf3/src/crypto/index.ts +71 -1239
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentdf/sdk",
3
- "version": "0.12.0",
3
+ "version": "0.13.0-beta.122",
4
4
  "description": "OpenTDF for the Web",
5
5
  "homepage": "https://github.com/opentdf/web-sdk",
6
6
  "bugs": {
package/src/auth/dpop.ts CHANGED
@@ -63,8 +63,8 @@ function b64u(input: Uint8Array | ArrayBuffer) {
63
63
  /**
64
64
  * Generates 32 random bytes and encodes them using base64url.
65
65
  */
66
- async function randomBytes(cryptoService: CryptoService) {
67
- return b64u(await cryptoService.randomBytes(32));
66
+ async function randomBytes() {
67
+ return b64u(crypto.getRandomValues(new Uint8Array(32)));
68
68
  }
69
69
 
70
70
  /**
@@ -210,7 +210,7 @@ export default async function DPoP(
210
210
  {
211
211
  ...additional,
212
212
  iat: epochTime(),
213
- jti: await randomBytes(cryptoService),
213
+ jti: await randomBytes(),
214
214
  htm,
215
215
  nonce,
216
216
  htu,
package/src/auth/oidc.ts CHANGED
@@ -11,7 +11,7 @@ import { type CryptoService, type KeyPair } from '../../tdf3/src/crypto/declarat
11
11
  export type CommonCredentials = {
12
12
  /** The OIDC client ID used for token issuance and exchange flows */
13
13
  clientId: string;
14
- /** The endpoint of the OIDC IdP to authenticate against, ex. 'https://virtru.com/auth' */
14
+ /** The endpoint of the OIDC IdP to authenticate against, ex. 'https://keycloak.opentdf.local/auth' */
15
15
  oidcOrigin: string;
16
16
  oidcTokenEndpoint?: string;
17
17
  oidcUserInfoEndpoint?: string;
@@ -176,6 +176,8 @@ export class AccessToken {
176
176
  }
177
177
  // Export opaque public key to PEM format for header
178
178
  const publicKeyPem = await this.cryptoService.exportPublicKeyPem(this.signingKey.publicKey);
179
+ // TODO: Rename to X-OpenTDF-PubKey; requires coordinated change with
180
+ // platform Keycloak mapper (lib/fixtures/keycloak.go `client.publickey`).
179
181
  headers['X-VirtruPubKey'] = base64.encode(publicKeyPem);
180
182
  headers.DPoP = await dpopFn(this.signingKey, this.cryptoService, url, 'POST');
181
183
  }
@@ -300,9 +302,9 @@ export class AccessToken {
300
302
  }
301
303
 
302
304
  async withCreds(httpReq: HttpRequest): Promise<HttpRequest> {
303
- if (!this.signingKey) {
305
+ if (this.config.dpopEnabled && !this.signingKey) {
304
306
  throw new ConfigurationError(
305
- 'Client public key was not set via `updateClientPublicKey` or passed in via constructor, cannot fetch OIDC token with valid Virtru claims'
307
+ 'Client public key was not set via `updateClientPublicKey` or passed in via constructor; required when DPoP is enabled'
306
308
  );
307
309
  }
308
310
  const accessToken = (this.currentAccessToken ??= await this.get());
package/src/version.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Exposes the released version number of the `@opentdf/sdk` package
3
3
  */
4
- export const version = '0.12.0'; // x-release-please-version
4
+ export const version = '0.13.0'; // x-release-please-version
5
5
 
6
6
  /**
7
7
  * A string name used to label requests as coming from this library client.
@@ -0,0 +1,118 @@
1
+ import {
2
+ type ECCurve,
3
+ type HkdfParams,
4
+ type KeyAlgorithm,
5
+ type KeyPair,
6
+ type PrivateKey,
7
+ type PublicKey,
8
+ type SymmetricKey,
9
+ } from '../declarations.js';
10
+ import { ConfigurationError } from '../../../../src/errors.js';
11
+ import { unwrapKey, wrapPrivateKey, wrapPublicKey, wrapSymmetricKey } from './keys.js';
12
+
13
+ /**
14
+ * Map ECCurve to Web Crypto named curve.
15
+ */
16
+ function curveToNamedCurve(curve: ECCurve): string {
17
+ switch (curve) {
18
+ case 'P-256':
19
+ return 'P-256';
20
+ case 'P-384':
21
+ return 'P-384';
22
+ case 'P-521':
23
+ return 'P-521';
24
+ default:
25
+ throw new ConfigurationError(`Unsupported curve: ${curve}`);
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Generate an EC key pair for ECDH key agreement.
31
+ */
32
+ export async function generateECKeyPair(curve: ECCurve = 'P-256'): Promise<KeyPair> {
33
+ const namedCurve = curveToNamedCurve(curve);
34
+
35
+ // Generate key pair for ECDH key agreement
36
+ const keyPair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve }, true, [
37
+ 'deriveBits',
38
+ ]);
39
+
40
+ // Map to KeyAlgorithm literal type
41
+ let algorithm: KeyAlgorithm;
42
+ switch (namedCurve) {
43
+ case 'P-256':
44
+ algorithm = 'ec:secp256r1';
45
+ break;
46
+ case 'P-384':
47
+ algorithm = 'ec:secp384r1';
48
+ break;
49
+ case 'P-521':
50
+ algorithm = 'ec:secp521r1';
51
+ break;
52
+ default:
53
+ throw new ConfigurationError(`Unsupported curve: ${namedCurve}`);
54
+ }
55
+
56
+ return {
57
+ publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
58
+ privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Perform ECDH key agreement followed by HKDF key derivation.
64
+ * Returns opaque symmetric key for symmetric encryption.
65
+ */
66
+ export async function deriveKeyFromECDH(
67
+ privateKey: PrivateKey,
68
+ publicKey: PublicKey,
69
+ hkdfParams: HkdfParams
70
+ ): Promise<SymmetricKey> {
71
+ // Unwrap the internal CryptoKeys
72
+ const privateKeyCrypto = unwrapKey(privateKey);
73
+ const publicKeyCrypto = unwrapKey(publicKey);
74
+
75
+ // Get curve from key metadata
76
+ const curve = publicKey.curve;
77
+ if (!curve) {
78
+ throw new ConfigurationError('EC curve not found on public key');
79
+ }
80
+
81
+ // Determine bits based on curve
82
+ const curveBits: Record<ECCurve, number> = {
83
+ 'P-256': 256,
84
+ 'P-384': 384,
85
+ // P-521 derives 528 bits (66 bytes)
86
+ 'P-521': 528,
87
+ };
88
+ const bits = curveBits[curve];
89
+
90
+ // Perform ECDH to get shared secret
91
+ const sharedSecret = await crypto.subtle.deriveBits(
92
+ { name: 'ECDH', public: publicKeyCrypto },
93
+ privateKeyCrypto,
94
+ bits
95
+ );
96
+
97
+ // Import shared secret as HKDF key material
98
+ const hkdfKey = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveKey']);
99
+
100
+ // Derive the final key using HKDF
101
+ const keyLength = hkdfParams.keyLength ?? 256;
102
+ const derivedKey = await crypto.subtle.deriveKey(
103
+ {
104
+ name: 'HKDF',
105
+ hash: hkdfParams.hash,
106
+ salt: hkdfParams.salt,
107
+ info: hkdfParams.info ?? new Uint8Array(0),
108
+ },
109
+ hkdfKey,
110
+ { name: 'AES-GCM', length: keyLength },
111
+ true,
112
+ ['encrypt', 'decrypt']
113
+ );
114
+
115
+ // Export the derived key as raw bytes and wrap as SymmetricKey
116
+ const keyBytes = await crypto.subtle.exportKey('raw', derivedKey);
117
+ return wrapSymmetricKey(new Uint8Array(keyBytes));
118
+ }
@@ -0,0 +1,420 @@
1
+ import {
2
+ type KeyAlgorithm,
3
+ type KeyOptions,
4
+ MIN_ASYMMETRIC_KEY_SIZE_BITS,
5
+ type PrivateKey,
6
+ type PublicKey,
7
+ type PublicKeyInfo,
8
+ } from '../declarations.js';
9
+ import { ConfigurationError } from '../../../../src/errors.js';
10
+ import { formatAsPem, removePemFormatting } from '../crypto-utils.js';
11
+ import { encodeArrayBuffer as hexEncode } from '../../../../src/encodings/hex.js';
12
+ import { decodeArrayBuffer as base64Decode } from '../../../../src/encodings/base64.js';
13
+ import { exportSPKI, importX509 } from 'jose';
14
+ import {
15
+ guessAlgorithmName,
16
+ guessCurveName,
17
+ toJwsAlg,
18
+ } from '../../../../src/crypto/pemPublicToCrypto.js';
19
+ import { unwrapKey, wrapPrivateKey, wrapPublicKey } from './keys.js';
20
+ import { rsaOaepSha1 } from './rsa.js';
21
+
22
+ /**
23
+ * Extract PEM public key from X.509 certificate or return PEM key as-is.
24
+ */
25
+ export async function extractPublicKeyPem(
26
+ certOrPem: string,
27
+ jwaAlgorithm?: string
28
+ ): Promise<string> {
29
+ // If it's a certificate, extract the public key
30
+ if (certOrPem.includes('-----BEGIN CERTIFICATE-----')) {
31
+ let alg = jwaAlgorithm;
32
+ if (!alg) {
33
+ // Auto-detect algorithm from certificate OIDs
34
+ const certBody = certOrPem.replace(/-----(BEGIN|END) CERTIFICATE-----|\s/g, '');
35
+ const certBytes = base64Decode(certBody);
36
+ const hex = hexEncode(certBytes);
37
+ alg = toJwsAlg(hex);
38
+ }
39
+ const cert = await importX509(certOrPem, alg, { extractable: true });
40
+ return exportSPKI(cert);
41
+ }
42
+
43
+ // If it's already a PEM public key, return as-is
44
+ if (certOrPem.includes('-----BEGIN PUBLIC KEY-----')) {
45
+ return certOrPem;
46
+ }
47
+
48
+ throw new ConfigurationError('Input must be a PEM-encoded certificate or public key');
49
+ }
50
+
51
+ const SUPPORTED_EC_CURVES = ['P-256', 'P-384', 'P-521'] as const;
52
+ type SupportedEcCurve = (typeof SUPPORTED_EC_CURVES)[number];
53
+
54
+ /**
55
+ * Decode base64url string and return byte length.
56
+ * Uses the existing base64 decoder which handles both standard and URL-safe encoding.
57
+ */
58
+ function base64urlByteLength(base64url: string): number {
59
+ // Add padding if needed (base64url omits padding)
60
+ const padding = (4 - (base64url.length % 4)) % 4;
61
+ const padded = base64url + '='.repeat(padding);
62
+ return base64Decode(padded).byteLength;
63
+ }
64
+
65
+ /**
66
+ * Extract EC curve from a public key by parsing ASN.1 OIDs.
67
+ * Reuses the existing guessCurveName function that checks for curve OIDs.
68
+ */
69
+ function extractEcCurveFromPublicKey(keyData: ArrayBuffer): SupportedEcCurve {
70
+ // Convert to hex for OID parsing
71
+ const hexKey = hexEncode(keyData);
72
+ // Use existing OID parser (returns 'P-256', 'P-384', or 'P-521')
73
+ const curveName = guessCurveName(hexKey);
74
+ return curveName as SupportedEcCurve;
75
+ }
76
+
77
+ /**
78
+ * Extract RSA modulus bit length by importing key and exporting as JWK.
79
+ * Uses Web Crypto's built-in ASN.1 parsing for robustness.
80
+ */
81
+ async function extractRsaModulusBitLength(keyData: ArrayBuffer): Promise<number> {
82
+ const key = await crypto.subtle.importKey(
83
+ 'spki',
84
+ keyData,
85
+ { name: 'RSA-OAEP', hash: 'SHA-256' },
86
+ true,
87
+ ['encrypt']
88
+ );
89
+ const jwk = await crypto.subtle.exportKey('jwk', key);
90
+ if (!jwk.n) {
91
+ throw new ConfigurationError('Invalid RSA key: missing modulus');
92
+ }
93
+ // JWK 'n' is base64url-encoded modulus
94
+ // Decode and count bytes, multiply by 8 for bits
95
+ return base64urlByteLength(jwk.n) * 8;
96
+ }
97
+
98
+ /**
99
+ * Import and validate a PEM public key, returning algorithm info.
100
+ * Uses JWK export for robust key parameter detection.
101
+ */
102
+ export async function parsePublicKeyPem(pem: string): Promise<PublicKeyInfo> {
103
+ // First extract public key if it's a certificate
104
+ let publicKeyPem = pem;
105
+ if (pem.includes('-----BEGIN CERTIFICATE-----')) {
106
+ publicKeyPem = await extractPublicKeyPem(pem);
107
+ }
108
+
109
+ if (!publicKeyPem.includes('-----BEGIN PUBLIC KEY-----')) {
110
+ throw new ConfigurationError('Input must be a PEM-encoded public key or certificate');
111
+ }
112
+
113
+ const keyData = base64Decode(removePemFormatting(publicKeyPem));
114
+
115
+ // Try RSA first - use JWK export to get modulus size
116
+ try {
117
+ const modulusBits = await extractRsaModulusBitLength(keyData);
118
+ let algorithm: PublicKeyInfo['algorithm'];
119
+ if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
120
+ throw new ConfigurationError(
121
+ `RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
122
+ );
123
+ } else if (modulusBits <= 2048) {
124
+ algorithm = 'rsa:2048';
125
+ } else if (modulusBits <= 4096) {
126
+ algorithm = 'rsa:4096';
127
+ } else {
128
+ throw new ConfigurationError(`Unsupported RSA key size: ${modulusBits} bits`);
129
+ }
130
+ return { algorithm, pem: publicKeyPem };
131
+ } catch (e) {
132
+ // If it's our own ConfigurationError, rethrow
133
+ if (e instanceof ConfigurationError) {
134
+ throw e;
135
+ }
136
+ // Not an RSA key, try EC next
137
+ }
138
+
139
+ // Try EC - parse curve from OID
140
+ try {
141
+ const detectedCurve = extractEcCurveFromPublicKey(keyData);
142
+ const curveMap = {
143
+ 'P-256': 'ec:secp256r1',
144
+ 'P-384': 'ec:secp384r1',
145
+ 'P-521': 'ec:secp521r1',
146
+ } as const;
147
+ return { algorithm: curveMap[detectedCurve], pem: publicKeyPem };
148
+ } catch {
149
+ // Not a valid EC key
150
+ }
151
+
152
+ throw new ConfigurationError('Unable to determine public key algorithm - unsupported key type');
153
+ }
154
+
155
+ /**
156
+ * Convert a JWK (JSON Web Key) to PEM format.
157
+ */
158
+ export async function jwkToPublicKeyPem(jwk: JsonWebKey): Promise<string> {
159
+ let key: CryptoKey;
160
+
161
+ if (jwk.kty === 'RSA') {
162
+ // RSA key
163
+ key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, [
164
+ 'encrypt',
165
+ ]);
166
+ } else if (jwk.kty === 'EC') {
167
+ // EC key
168
+ const crv = jwk.crv;
169
+ if (!crv || !['P-256', 'P-384', 'P-521'].includes(crv)) {
170
+ throw new ConfigurationError(`Unsupported EC curve: ${crv}`);
171
+ }
172
+ key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: crv }, true, []);
173
+ } else {
174
+ throw new ConfigurationError(`Unsupported JWK key type: ${jwk.kty}`);
175
+ }
176
+
177
+ const spkiBuffer = await crypto.subtle.exportKey('spki', key);
178
+ return formatAsPem(spkiBuffer, 'PUBLIC KEY');
179
+ }
180
+
181
+ /**
182
+ * Convert a PEM public key to JWK format.
183
+ * Returns only public key components (no private key data).
184
+ */
185
+ export async function publicKeyPemToJwk(publicKeyPem: string): Promise<JsonWebKey> {
186
+ const keyDataBase64 = removePemFormatting(publicKeyPem);
187
+ const keyBuffer = base64Decode(keyDataBase64);
188
+ const hex = hexEncode(keyBuffer);
189
+
190
+ // Detect key type using OID
191
+ const algorithmName = guessAlgorithmName(hex);
192
+
193
+ if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
194
+ // EC key - detect curve from OID
195
+ const namedCurve = guessCurveName(hex);
196
+ const key = await crypto.subtle.importKey(
197
+ 'spki',
198
+ keyBuffer,
199
+ { name: 'ECDSA', namedCurve },
200
+ true,
201
+ ['verify']
202
+ );
203
+ const jwk = await crypto.subtle.exportKey('jwk', key);
204
+ // Return only public key components
205
+ const { kty, crv, x, y } = jwk;
206
+ return { kty, crv, x, y };
207
+ } else {
208
+ // RSA key
209
+ const key = await crypto.subtle.importKey(
210
+ 'spki',
211
+ keyBuffer,
212
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
213
+ true,
214
+ ['verify']
215
+ );
216
+ const jwk = await crypto.subtle.exportKey('jwk', key);
217
+ // Return only public key components
218
+ const { kty, e, n } = jwk;
219
+ return { kty, e, n };
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Import a PEM public key as an opaque key.
225
+ */
226
+ export async function importPublicKey(pem: string, options: KeyOptions): Promise<PublicKey> {
227
+ const { usage = 'encrypt', extractable = true, algorithmHint } = options;
228
+
229
+ // Detect algorithm from PEM; also normalises certificates → plain SPKI PEM.
230
+ const keyInfo = await parsePublicKeyPem(pem);
231
+ const algorithm = algorithmHint || keyInfo.algorithm;
232
+ // Use keyInfo.pem (normalised SPKI) not the original pem, which may be a certificate.
233
+ // Passing raw X.509 DER bytes to crypto.subtle.importKey('spki') would throw DataError.
234
+ const keyData = removePemFormatting(keyInfo.pem);
235
+ const keyBuffer = base64Decode(keyData);
236
+
237
+ // Determine Web Crypto algorithm and usages based on key type and usage
238
+ let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
239
+ let keyUsages: KeyUsage[];
240
+
241
+ if (algorithm.startsWith('rsa:')) {
242
+ if (usage === 'encrypt') {
243
+ cryptoAlgorithm = rsaOaepSha1();
244
+ keyUsages = ['encrypt'];
245
+ } else if (usage === 'sign') {
246
+ cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
247
+ keyUsages = ['verify'];
248
+ } else {
249
+ throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
250
+ }
251
+ } else if (algorithm.startsWith('ec:')) {
252
+ const curve = algorithm.split(':')[1];
253
+ const namedCurve =
254
+ curve === 'secp256r1'
255
+ ? 'P-256'
256
+ : curve === 'secp384r1'
257
+ ? 'P-384'
258
+ : curve === 'secp521r1'
259
+ ? 'P-521'
260
+ : (() => {
261
+ throw new ConfigurationError(`Unsupported EC curve: ${curve}`);
262
+ })();
263
+
264
+ if (usage === 'derive') {
265
+ cryptoAlgorithm = { name: 'ECDH', namedCurve };
266
+ keyUsages = [];
267
+ } else if (usage === 'sign') {
268
+ cryptoAlgorithm = { name: 'ECDSA', namedCurve };
269
+ keyUsages = ['verify'];
270
+ } else {
271
+ throw new ConfigurationError('EC keys only support usage: derive or sign');
272
+ }
273
+ } else {
274
+ throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
275
+ }
276
+
277
+ // Import as CryptoKey
278
+ const cryptoKey = await crypto.subtle.importKey(
279
+ 'spki',
280
+ keyBuffer,
281
+ cryptoAlgorithm,
282
+ extractable,
283
+ keyUsages
284
+ );
285
+
286
+ return wrapPublicKey(cryptoKey, algorithm);
287
+ }
288
+
289
+ /**
290
+ * Import a PEM private key as an opaque key.
291
+ */
292
+ export async function importPrivateKey(pem: string, options: KeyOptions): Promise<PrivateKey> {
293
+ const { usage = 'encrypt', extractable = true, algorithmHint } = options;
294
+
295
+ // Detect algorithm from PEM structure (similar to public key detection)
296
+ // For now, use algorithmHint if provided, otherwise detect from key structure
297
+ let algorithm: KeyAlgorithm;
298
+
299
+ const keyData = removePemFormatting(pem);
300
+ const keyBuffer = base64Decode(keyData);
301
+
302
+ if (algorithmHint) {
303
+ algorithm = algorithmHint;
304
+ } else {
305
+ // PKCS#8 PrivateKeyInfo embeds the same AlgorithmIdentifier OIDs as SPKI,
306
+ // so guessAlgorithmName / guessCurveName work on private key bytes too.
307
+ const hex = hexEncode(keyBuffer);
308
+ const algorithmName = guessAlgorithmName(hex); // throws on unrecognised OID
309
+ if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
310
+ const namedCurve = guessCurveName(hex);
311
+ const curveMap: Record<string, KeyAlgorithm> = {
312
+ 'P-256': 'ec:secp256r1',
313
+ 'P-384': 'ec:secp384r1',
314
+ 'P-521': 'ec:secp521r1',
315
+ };
316
+ const mapped = curveMap[namedCurve];
317
+ if (!mapped)
318
+ throw new ConfigurationError(`Unsupported EC curve in private key: ${namedCurve}`);
319
+ algorithm = mapped;
320
+ } else {
321
+ // RSA — determine key size by importing and reading modulus length from JWK
322
+ const tempKey = await crypto.subtle.importKey(
323
+ 'pkcs8',
324
+ keyBuffer,
325
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
326
+ true,
327
+ ['sign']
328
+ );
329
+ const jwk = await crypto.subtle.exportKey('jwk', tempKey);
330
+ if (!jwk.n) {
331
+ throw new ConfigurationError('Invalid RSA private key: missing modulus');
332
+ }
333
+ const modulusBits = base64urlByteLength(jwk.n) * 8;
334
+ if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
335
+ throw new ConfigurationError(
336
+ `RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
337
+ );
338
+ }
339
+ algorithm = modulusBits <= 2048 ? 'rsa:2048' : 'rsa:4096';
340
+ }
341
+ }
342
+
343
+ // Determine Web Crypto algorithm and usages
344
+ let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
345
+ let keyUsages: KeyUsage[];
346
+
347
+ if (algorithm.startsWith('rsa:')) {
348
+ if (usage === 'encrypt') {
349
+ cryptoAlgorithm = rsaOaepSha1();
350
+ keyUsages = ['decrypt'];
351
+ } else if (usage === 'sign') {
352
+ cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
353
+ keyUsages = ['sign'];
354
+ } else {
355
+ throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
356
+ }
357
+ } else if (algorithm.startsWith('ec:')) {
358
+ const curve = algorithm.split(':')[1];
359
+ const namedCurve =
360
+ curve === 'secp256r1'
361
+ ? 'P-256'
362
+ : curve === 'secp384r1'
363
+ ? 'P-384'
364
+ : curve === 'secp521r1'
365
+ ? 'P-521'
366
+ : (() => {
367
+ throw new ConfigurationError(`Unsupported EC curve: ${curve}`);
368
+ })();
369
+
370
+ if (usage === 'derive') {
371
+ cryptoAlgorithm = { name: 'ECDH', namedCurve };
372
+ keyUsages = ['deriveBits'];
373
+ } else if (usage === 'sign') {
374
+ cryptoAlgorithm = { name: 'ECDSA', namedCurve };
375
+ keyUsages = ['sign'];
376
+ } else {
377
+ throw new ConfigurationError('EC keys only support usage: derive or sign');
378
+ }
379
+ } else {
380
+ throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
381
+ }
382
+
383
+ // Import as CryptoKey
384
+ const cryptoKey = await crypto.subtle.importKey(
385
+ 'pkcs8',
386
+ keyBuffer,
387
+ cryptoAlgorithm,
388
+ extractable,
389
+ keyUsages
390
+ );
391
+
392
+ return wrapPrivateKey(cryptoKey, algorithm);
393
+ }
394
+
395
+ /**
396
+ * Export an opaque public key to PEM format.
397
+ */
398
+ export async function exportPublicKeyPem(key: PublicKey): Promise<string> {
399
+ const cryptoKey = unwrapKey(key);
400
+ const keyBuffer = await crypto.subtle.exportKey('spki', cryptoKey);
401
+ return formatAsPem(keyBuffer, 'PUBLIC KEY');
402
+ }
403
+
404
+ /**
405
+ * Export an opaque private key to PEM format.
406
+ * ONLY USE FOR TESTING/DEVELOPMENT. Private keys should NOT be exportable in secure environments.
407
+ */
408
+ export async function exportPrivateKeyPem(key: PrivateKey): Promise<string> {
409
+ const cryptoKey = unwrapKey(key);
410
+ const keyBuffer = await crypto.subtle.exportKey('pkcs8', cryptoKey);
411
+ return formatAsPem(keyBuffer, 'PRIVATE KEY');
412
+ }
413
+
414
+ /**
415
+ * Export an opaque public key to JWK format.
416
+ */
417
+ export async function exportPublicKeyJwk(key: PublicKey): Promise<JsonWebKey> {
418
+ const cryptoKey = unwrapKey(key);
419
+ return await crypto.subtle.exportKey('jwk', cryptoKey);
420
+ }
@@ -0,0 +1,86 @@
1
+ import {
2
+ type KeyAlgorithm,
3
+ type PrivateKey,
4
+ type PublicKey,
5
+ type SymmetricKey,
6
+ } from '../declarations.js';
7
+
8
+ /**
9
+ * Wrap a CryptoKey as an opaque PublicKey.
10
+ * @internal
11
+ */
12
+ export function wrapPublicKey(key: CryptoKey, algorithm: KeyAlgorithm): PublicKey {
13
+ const result: any = {
14
+ _brand: 'PublicKey',
15
+ algorithm,
16
+ _internal: key,
17
+ };
18
+ if (algorithm.startsWith('rsa:')) {
19
+ result.modulusBits = parseInt(algorithm.split(':')[1], 10);
20
+ } else if (algorithm.startsWith('ec:')) {
21
+ const curvePart = algorithm.split(':')[1];
22
+ result.curve =
23
+ curvePart === 'secp256r1'
24
+ ? 'P-256'
25
+ : curvePart === 'secp384r1'
26
+ ? 'P-384'
27
+ : curvePart === 'secp521r1'
28
+ ? 'P-521'
29
+ : undefined;
30
+ }
31
+ return result as PublicKey;
32
+ }
33
+
34
+ /**
35
+ * Wrap a CryptoKey as an opaque PrivateKey.
36
+ * @internal
37
+ */
38
+ export function wrapPrivateKey(key: CryptoKey, algorithm: KeyAlgorithm): PrivateKey {
39
+ const result: any = {
40
+ _brand: 'PrivateKey',
41
+ algorithm,
42
+ _internal: key,
43
+ };
44
+ if (algorithm.startsWith('rsa:')) {
45
+ result.modulusBits = parseInt(algorithm.split(':')[1], 10);
46
+ } else if (algorithm.startsWith('ec:')) {
47
+ const curvePart = algorithm.split(':')[1];
48
+ result.curve =
49
+ curvePart === 'secp256r1'
50
+ ? 'P-256'
51
+ : curvePart === 'secp384r1'
52
+ ? 'P-384'
53
+ : curvePart === 'secp521r1'
54
+ ? 'P-521'
55
+ : undefined;
56
+ }
57
+ return result as PrivateKey;
58
+ }
59
+
60
+ /**
61
+ * Unwrap an opaque key to get the internal CryptoKey.
62
+ * @internal
63
+ */
64
+ export function unwrapKey(key: PublicKey | PrivateKey): CryptoKey {
65
+ return (key as any)._internal;
66
+ }
67
+
68
+ /**
69
+ * Wrap raw key bytes as an opaque SymmetricKey.
70
+ * @internal
71
+ */
72
+ export function wrapSymmetricKey(keyBytes: Uint8Array): SymmetricKey {
73
+ return {
74
+ _brand: 'SymmetricKey',
75
+ length: keyBytes.length * 8, // bits
76
+ _internal: keyBytes,
77
+ } as SymmetricKey;
78
+ }
79
+
80
+ /**
81
+ * Unwrap an opaque SymmetricKey to get raw bytes.
82
+ * @internal
83
+ */
84
+ export function unwrapSymmetricKey(key: SymmetricKey): Uint8Array {
85
+ return (key as any)._internal;
86
+ }