@covia/covia-sdk 1.19.1 → 1.20.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/dist/index.d.mts CHANGED
@@ -203,6 +203,48 @@ declare abstract class Asset {
203
203
  invoke(input?: unknown, options?: InvokeOptions): Promise<Job>;
204
204
  }
205
205
 
206
+ /**
207
+ * Ed25519 signers: the key-holding half of every signing path, abstracted so
208
+ * the private key need not be readable bytes.
209
+ *
210
+ * A {@link rawKeySigner} wraps a 32-byte key (the classic path). A
211
+ * {@link webCryptoSigner} wraps a WebCrypto `CryptoKeyPair` whose private key
212
+ * can be **non-extractable**: it signs, but no script can read it back as
213
+ * bytes, and it persists in IndexedDB as a structured-cloneable `CryptoKey`.
214
+ * WebCrypto signing is async, so the {@link Ed25519Signer} contract is too.
215
+ *
216
+ * Ed25519 is deterministic (RFC 8032): the same key and message give the same
217
+ * signature on either path, so tokens are identical whichever signer made them.
218
+ */
219
+ /** Signs with an Ed25519 key that may not be readable as bytes. */
220
+ interface Ed25519Signer {
221
+ /** 32-byte raw public key. */
222
+ readonly publicKey: Uint8Array;
223
+ /** Ed25519 signature (64 bytes) over `data`. */
224
+ sign(data: Uint8Array): Promise<Uint8Array>;
225
+ }
226
+ /** A signer over a raw 32-byte private key (synchronous @noble signing underneath). */
227
+ declare function rawKeySigner(privateKey: Uint8Array): Ed25519Signer;
228
+ /**
229
+ * A signer over a WebCrypto Ed25519 keypair. The private key may be (and
230
+ * normally should be) non-extractable; the public key always is exportable.
231
+ */
232
+ declare function webCryptoSigner(keyPair: CryptoKeyPair): Promise<Ed25519Signer>;
233
+ /** Generate a WebCrypto Ed25519 keypair whose private key cannot be exported. */
234
+ declare function generateNonExtractableKeyPair(): Promise<CryptoKeyPair>;
235
+ /**
236
+ * Import an existing 32-byte private key as a non-extractable WebCrypto
237
+ * keypair — the one-time migration from a stored hex/raw key. The DID is
238
+ * unchanged. The caller should delete its own copy of the raw key afterwards.
239
+ */
240
+ declare function importNonExtractableKey(privateKey: Uint8Array): Promise<CryptoKeyPair>;
241
+ /**
242
+ * Whether this runtime can sign with WebCrypto Ed25519 (current Chrome,
243
+ * Firefox, Safari 17+ and Node). Apps without it fall back to a raw-key
244
+ * signer. Probed once, by generating and signing with a throwaway key.
245
+ */
246
+ declare function isWebCryptoEd25519Supported(): Promise<boolean>;
247
+
206
248
  /**
207
249
  * Abstract base class for authentication strategies.
208
250
  * Subclass this to implement custom authentication.
@@ -224,8 +266,11 @@ declare abstract class Auth {
224
266
  * @param audience - The venue's DID, supplied by the transport. Providers
225
267
  * that bind tokens to the venue's identity (e.g. {@link Ed25519Auth}) use it
226
268
  * as the JWT `aud`; others ignore it.
269
+ * @returns Nothing, or a promise for providers that sign asynchronously
270
+ * (e.g. {@link Ed25519Auth.fromSigner} over a WebCrypto key). The transport
271
+ * awaits it before sending, so callers of `apply` must await it too.
227
272
  */
228
- abstract apply(headers: Record<string, string>, audience?: string): void;
273
+ abstract apply(headers: Record<string, string>, audience?: string): void | Promise<void>;
229
274
  }
230
275
  /** No-op authentication provider. Sends no credentials. */
231
276
  declare class NoAuth extends Auth {
@@ -262,23 +307,34 @@ declare class BasicAuth extends Auth {
262
307
  * client's Ed25519 private key. The server verifies the signature and
263
308
  * extracts the caller's DID from the `sub` claim.
264
309
  *
310
+ * Construct it from a raw 32-byte key, or with {@link Ed25519Auth.fromSigner}
311
+ * from an {@link Ed25519Signer} — e.g. a non-extractable WebCrypto key, which
312
+ * signs without the key ever being readable by page scripts. Signer-backed
313
+ * instances sign asynchronously; the SDK transport awaits them.
314
+ *
265
315
  * Example:
266
316
  * const auth = Ed25519Auth.generate();
267
317
  * console.log(auth.getDID()); // did:key:z6Mk...
268
318
  * const venue = await Grid.connect("https://your-venue.example.com", auth);
319
+ *
320
+ * // Non-extractable key (browser):
321
+ * const signer = await webCryptoSigner(await generateNonExtractableKeyPair());
322
+ * const venue2 = await Grid.connect("https://your-venue.example.com", Ed25519Auth.fromSigner(signer));
269
323
  */
270
324
  declare class Ed25519Auth extends Auth {
271
- private _privateKey;
325
+ /** Present only for raw-key instances; signer-backed ones never see key bytes. */
326
+ private _privateKey?;
327
+ private _signer;
272
328
  private _publicKey;
273
329
  private _did;
274
330
  private _lifetime;
275
331
  private _audience?;
276
332
  /**
277
- * @param privateKey - 32-byte Ed25519 private key
333
+ * @param key - 32-byte Ed25519 private key, or an {@link Ed25519Signer}
278
334
  * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
279
335
  */
280
- constructor(privateKey: Uint8Array, tokenLifetimeSeconds?: number);
281
- apply(headers: Record<string, string>, audience?: string): void;
336
+ constructor(key: Uint8Array | Ed25519Signer, tokenLifetimeSeconds?: number);
337
+ apply(headers: Record<string, string>, audience?: string): void | Promise<void>;
282
338
  /**
283
339
  * Mint a bearer-usable identity JWT for this key — the same token
284
340
  * {@link apply} attaches to every request, exposed for callers that need
@@ -290,10 +346,19 @@ declare class Ed25519Auth extends Auth {
290
346
  * at any venue that accepts the caller's DID, so minting one is refused
291
347
  * rather than silently weakened.
292
348
  *
349
+ * Raw-key instances only: a signer-backed instance signs asynchronously,
350
+ * so use {@link mintIdentityToken}, which works for both.
351
+ *
293
352
  * @param audience - The venue DID the token is bound to (`aud` claim).
294
353
  * @param lifetimeSeconds - Token lifetime; defaults to this instance's.
295
354
  */
296
355
  identityToken(audience?: string, lifetimeSeconds?: number): string;
356
+ /**
357
+ * Async {@link identityToken} that works for raw-key and signer-backed
358
+ * instances alike. Same token, same audience rules.
359
+ */
360
+ mintIdentityToken(audience?: string, lifetimeSeconds?: number): Promise<string>;
361
+ private resolveAudience;
297
362
  /** The caller's DID derived from the public key. */
298
363
  getDID(): string;
299
364
  /**
@@ -308,6 +373,11 @@ declare class Ed25519Auth extends Auth {
308
373
  static generate(tokenLifetimeSeconds?: number): Ed25519Auth;
309
374
  /** Create from a hex-encoded private key string. */
310
375
  static fromHex(privateKeyHex: string, tokenLifetimeSeconds?: number): Ed25519Auth;
376
+ /**
377
+ * Create from an {@link Ed25519Signer}, e.g. `await webCryptoSigner(keyPair)`
378
+ * over a non-extractable WebCrypto key. Requests sign asynchronously.
379
+ */
380
+ static fromSigner(signer: Ed25519Signer, tokenLifetimeSeconds?: number): Ed25519Auth;
311
381
  }
312
382
  /**
313
383
  * @deprecated Renamed to {@link Ed25519Auth} for cross-SDK consistency
@@ -367,7 +437,7 @@ interface VenueRequestContext {
367
437
  baseUrl: string;
368
438
  venueId: string;
369
439
  auth: {
370
- apply(headers: Record<string, string>, audience?: string): void;
440
+ apply(headers: Record<string, string>, audience?: string): void | Promise<void>;
371
441
  };
372
442
  }
373
443
 
@@ -2677,6 +2747,7 @@ declare function didFromPublicKey(publicKey: Uint8Array): string;
2677
2747
  * `ucans` request array and relayed across cross-venue hops. Delegation chains
2678
2748
  * embed parent tokens as JWT strings in `prf`.
2679
2749
  */
2750
+
2680
2751
  /** The ability that instructs a venue to relay a cross-venue hop as itself. */
2681
2752
  declare const VENUE_RELAY = "venue/relay";
2682
2753
  interface UCANCapability {
@@ -2700,6 +2771,11 @@ declare function didFor(privateKey: Uint8Array): string;
2700
2771
  * @param proofs parent UCAN JWT strings (`prf`) for delegation chains
2701
2772
  */
2702
2773
  declare function createUCANJWT(privateKey: Uint8Array, audienceDID: string, att: UCANCapability[], lifetimeSeconds: number | null, proofs?: string[]): string;
2774
+ /**
2775
+ * {@link createUCANJWT} through an {@link Ed25519Signer}, for issuers whose
2776
+ * key is not readable bytes (e.g. a non-extractable WebCrypto key). Same token.
2777
+ */
2778
+ declare function createUCANJWTWith(signer: Ed25519Signer, audienceDID: string, att: UCANCapability[], lifetimeSeconds: number | null, proofs?: string[]): Promise<string>;
2703
2779
  /**
2704
2780
  * Mint an **identity token**: a UCAN with an EMPTY attenuation list, audienced
2705
2781
  * to `venueDID`. Pure proof of identity — it grants nothing, and being
@@ -2716,6 +2792,8 @@ declare function identityToken(privateKey: Uint8Array, venueDID: string, lifetim
2716
2792
  * in issuance.
2717
2793
  */
2718
2794
  declare function grant(ownerPrivateKey: Uint8Array, audienceDID: string, withResource: string, can: string, lifetimeSeconds: number): string;
2795
+ /** {@link grant} through an {@link Ed25519Signer}. */
2796
+ declare function grantWith(ownerSigner: Ed25519Signer, audienceDID: string, withResource: string, can: string, lifetimeSeconds: number): Promise<string>;
2719
2797
  /**
2720
2798
  * Mint a **relay delegation**: instructs and authorises `venueDID` to make a
2721
2799
  * cross-venue hop authenticated as itself, exercising the caller's authority.
@@ -2724,5 +2802,7 @@ declare function grant(ownerPrivateKey: Uint8Array, audienceDID: string, withRes
2724
2802
  * authenticated caller (COG-15).
2725
2803
  */
2726
2804
  declare function relayDelegation(privateKey: Uint8Array, venueDID: string, lifetimeSeconds: number, caps?: UCANCapability[]): string;
2805
+ /** {@link relayDelegation} through an {@link Ed25519Signer}. */
2806
+ declare function relayDelegationWith(signer: Ed25519Signer, venueDID: string, lifetimeSeconds: number, caps?: UCANCapability[]): Promise<string>;
2727
2807
 
2728
- export { type A2AAuthRef, type A2AImportAgentInput, type A2AImportAgentResult, A2AManager, type A2AMessage, type A2APart, type A2ATask, type AdapterInfo, AdapterManager, type AdaptersResult, Agent, type AgentCancelTaskInput, type AgentCard, type AgentChatInput, type AgentChatResult, type AgentCompactedSegment, type AgentCompleteTaskResult, type AgentContextInput, type AgentCreateInput, type AgentCreateResult, type AgentCycleEndEvent, type AgentCycleStartEvent, type AgentDeleteInput, type AgentDeleteResult, type AgentEvent, type AgentEventEnvelope, type AgentFailTaskResult, type AgentForkInput, type AgentForkResult, type AgentInferenceEndEvent, type AgentInferenceStartEvent, type AgentInfoResult, type AgentListInput, type AgentListResult, AgentManager, type AgentMessageInput, type AgentMessageResult, type AgentRenameSessionResult, type AgentRequestInput, type AgentRequestResult, type AgentResumeInput, type AgentRunEndEvent, type AgentRunStartEvent, type AgentSession, type AgentSessionListOptions, type AgentSessionMessage, type AgentSessionMetadata, AgentSessionNotFoundError, type AgentSessionPage, type AgentSessionRole, AgentStatus, type AgentStatusEvent, type AgentSuspendResult, type AgentToolResultEvent, type AgentToolStartEvent, type AgentTriggerInput, type AgentTriggerResult, type AgentUpdateInput, Asset, type AssetID, type AssetList, type AssetListItem, type AssetListOptions, AssetManager, type AssetMetadata, type AssetMetadataStore, AssetNotFoundError, type AssetPinResult, type AssetSummary, Auth, type AuthenticationKeyEntry, type AuthenticationKeysMap, type AuthenticationKeysResult, type AuthenticatorRevokeResult, BasicAuth, BearerAuth, ChatSession, type ConnectionAttempt, type ContentDetails, type ContentHashResult, CoviaConnectionError, type CoviaConnectionErrorOptions, CoviaError, CoviaTimeoutError, type Credentials, CredentialsHTTP, type DIDDocument, type DIDURL, type DLFSDrivesResult, type DLFSEntry, type DLFSListResult, DLFSManager, DataAsset, Ed25519Auth, type ExecutionScope, type ExpandedAssetList, type FunctionInfo, type FunctionsResult, Grid, GridError, type GroupCount, type InvokeOptions, type InvokePayload, Job, JobFailedError, type JobHistoryOptions, type JobHistoryPage, JobManager, type JobMetadata, JobNotFoundError, JobStatus, KeyPairAuth, type MCPContent, type MCPDiscovery, MCPError, MCPManager, type MCPTool, type MCPToolPage, type MCPToolResult, type MemoryChange, type MemoryEntry, MemoryManager, type MyAssetList, Namespace, NoAuth, NotFoundError, Operation, type OperationDetails, type OperationInfo, OperationManager, type OperationPayload, type OperationRunner, RateLimitError, RunStatus, type SSEEvent, ScopedWorkspace, type SecretExtractInput, type SecretExtractResult, SecretManager, type SecretSetInput, type SecretSetResult, type Skill, type SkillFacet, SkillManager, type SkillMetadata, type StatsData, type StatusData, type UCANAttenuation, type UCANCapability, type UCANIssueInput, type UCANIssueResult, UCANManager, type UCANVerifyResult, UnsupportedVenueFeatureError, type UserInfo, type UserListResult, UserManager, type UserSummary, VENUE_RELAY, Venue, type VenueConstructor, type VenueData, VenueIdentityChangedError, type VenueInterface, type VenueOptions, type WorkspaceAggregateResult, type WorkspaceAppendInput, type WorkspaceAppendResult, type WorkspaceCopyResult, type WorkspaceCountResult, type WorkspaceDeleteInput, type WorkspaceDeleteResult, type WorkspaceFieldValue, type WorkspaceInspectInput, type WorkspaceInspectResult, type WorkspaceListInput, type WorkspaceListResult, WorkspaceManager, type WorkspaceProjectedList, type WorkspaceReadInput, type WorkspaceReadResult, type WorkspaceSliceInput, type WorkspaceSliceResult, type WorkspaceWriteInput, type WorkspaceWriteResult, assetHash, createSSEEvent, createUCANJWT, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, hexToPrivateKey, identityToken, isDid, isJobComplete, isJobFinished, isJobPaused, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, relayDelegation, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates };
2808
+ export { type A2AAuthRef, type A2AImportAgentInput, type A2AImportAgentResult, A2AManager, type A2AMessage, type A2APart, type A2ATask, type AdapterInfo, AdapterManager, type AdaptersResult, Agent, type AgentCancelTaskInput, type AgentCard, type AgentChatInput, type AgentChatResult, type AgentCompactedSegment, type AgentCompleteTaskResult, type AgentContextInput, type AgentCreateInput, type AgentCreateResult, type AgentCycleEndEvent, type AgentCycleStartEvent, type AgentDeleteInput, type AgentDeleteResult, type AgentEvent, type AgentEventEnvelope, type AgentFailTaskResult, type AgentForkInput, type AgentForkResult, type AgentInferenceEndEvent, type AgentInferenceStartEvent, type AgentInfoResult, type AgentListInput, type AgentListResult, AgentManager, type AgentMessageInput, type AgentMessageResult, type AgentRenameSessionResult, type AgentRequestInput, type AgentRequestResult, type AgentResumeInput, type AgentRunEndEvent, type AgentRunStartEvent, type AgentSession, type AgentSessionListOptions, type AgentSessionMessage, type AgentSessionMetadata, AgentSessionNotFoundError, type AgentSessionPage, type AgentSessionRole, AgentStatus, type AgentStatusEvent, type AgentSuspendResult, type AgentToolResultEvent, type AgentToolStartEvent, type AgentTriggerInput, type AgentTriggerResult, type AgentUpdateInput, Asset, type AssetID, type AssetList, type AssetListItem, type AssetListOptions, AssetManager, type AssetMetadata, type AssetMetadataStore, AssetNotFoundError, type AssetPinResult, type AssetSummary, Auth, type AuthenticationKeyEntry, type AuthenticationKeysMap, type AuthenticationKeysResult, type AuthenticatorRevokeResult, BasicAuth, BearerAuth, ChatSession, type ConnectionAttempt, type ContentDetails, type ContentHashResult, CoviaConnectionError, type CoviaConnectionErrorOptions, CoviaError, CoviaTimeoutError, type Credentials, CredentialsHTTP, type DIDDocument, type DIDURL, type DLFSDrivesResult, type DLFSEntry, type DLFSListResult, DLFSManager, DataAsset, Ed25519Auth, type Ed25519Signer, type ExecutionScope, type ExpandedAssetList, type FunctionInfo, type FunctionsResult, Grid, GridError, type GroupCount, type InvokeOptions, type InvokePayload, Job, JobFailedError, type JobHistoryOptions, type JobHistoryPage, JobManager, type JobMetadata, JobNotFoundError, JobStatus, KeyPairAuth, type MCPContent, type MCPDiscovery, MCPError, MCPManager, type MCPTool, type MCPToolPage, type MCPToolResult, type MemoryChange, type MemoryEntry, MemoryManager, type MyAssetList, Namespace, NoAuth, NotFoundError, Operation, type OperationDetails, type OperationInfo, OperationManager, type OperationPayload, type OperationRunner, RateLimitError, RunStatus, type SSEEvent, ScopedWorkspace, type SecretExtractInput, type SecretExtractResult, SecretManager, type SecretSetInput, type SecretSetResult, type Skill, type SkillFacet, SkillManager, type SkillMetadata, type StatsData, type StatusData, type UCANAttenuation, type UCANCapability, type UCANIssueInput, type UCANIssueResult, UCANManager, type UCANVerifyResult, UnsupportedVenueFeatureError, type UserInfo, type UserListResult, UserManager, type UserSummary, VENUE_RELAY, Venue, type VenueConstructor, type VenueData, VenueIdentityChangedError, type VenueInterface, type VenueOptions, type WorkspaceAggregateResult, type WorkspaceAppendInput, type WorkspaceAppendResult, type WorkspaceCopyResult, type WorkspaceCountResult, type WorkspaceDeleteInput, type WorkspaceDeleteResult, type WorkspaceFieldValue, type WorkspaceInspectInput, type WorkspaceInspectResult, type WorkspaceListInput, type WorkspaceListResult, WorkspaceManager, type WorkspaceProjectedList, type WorkspaceReadInput, type WorkspaceReadResult, type WorkspaceSliceInput, type WorkspaceSliceResult, type WorkspaceWriteInput, type WorkspaceWriteResult, assetHash, createSSEEvent, createUCANJWT, createUCANJWTWith, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, generateNonExtractableKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, grantWith, hexToPrivateKey, identityToken, importNonExtractableKey, isDid, isJobComplete, isJobFinished, isJobPaused, isWebCryptoEd25519Supported, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, rawKeySigner, relayDelegation, relayDelegationWith, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates, webCryptoSigner };
package/dist/index.d.ts CHANGED
@@ -203,6 +203,48 @@ declare abstract class Asset {
203
203
  invoke(input?: unknown, options?: InvokeOptions): Promise<Job>;
204
204
  }
205
205
 
206
+ /**
207
+ * Ed25519 signers: the key-holding half of every signing path, abstracted so
208
+ * the private key need not be readable bytes.
209
+ *
210
+ * A {@link rawKeySigner} wraps a 32-byte key (the classic path). A
211
+ * {@link webCryptoSigner} wraps a WebCrypto `CryptoKeyPair` whose private key
212
+ * can be **non-extractable**: it signs, but no script can read it back as
213
+ * bytes, and it persists in IndexedDB as a structured-cloneable `CryptoKey`.
214
+ * WebCrypto signing is async, so the {@link Ed25519Signer} contract is too.
215
+ *
216
+ * Ed25519 is deterministic (RFC 8032): the same key and message give the same
217
+ * signature on either path, so tokens are identical whichever signer made them.
218
+ */
219
+ /** Signs with an Ed25519 key that may not be readable as bytes. */
220
+ interface Ed25519Signer {
221
+ /** 32-byte raw public key. */
222
+ readonly publicKey: Uint8Array;
223
+ /** Ed25519 signature (64 bytes) over `data`. */
224
+ sign(data: Uint8Array): Promise<Uint8Array>;
225
+ }
226
+ /** A signer over a raw 32-byte private key (synchronous @noble signing underneath). */
227
+ declare function rawKeySigner(privateKey: Uint8Array): Ed25519Signer;
228
+ /**
229
+ * A signer over a WebCrypto Ed25519 keypair. The private key may be (and
230
+ * normally should be) non-extractable; the public key always is exportable.
231
+ */
232
+ declare function webCryptoSigner(keyPair: CryptoKeyPair): Promise<Ed25519Signer>;
233
+ /** Generate a WebCrypto Ed25519 keypair whose private key cannot be exported. */
234
+ declare function generateNonExtractableKeyPair(): Promise<CryptoKeyPair>;
235
+ /**
236
+ * Import an existing 32-byte private key as a non-extractable WebCrypto
237
+ * keypair — the one-time migration from a stored hex/raw key. The DID is
238
+ * unchanged. The caller should delete its own copy of the raw key afterwards.
239
+ */
240
+ declare function importNonExtractableKey(privateKey: Uint8Array): Promise<CryptoKeyPair>;
241
+ /**
242
+ * Whether this runtime can sign with WebCrypto Ed25519 (current Chrome,
243
+ * Firefox, Safari 17+ and Node). Apps without it fall back to a raw-key
244
+ * signer. Probed once, by generating and signing with a throwaway key.
245
+ */
246
+ declare function isWebCryptoEd25519Supported(): Promise<boolean>;
247
+
206
248
  /**
207
249
  * Abstract base class for authentication strategies.
208
250
  * Subclass this to implement custom authentication.
@@ -224,8 +266,11 @@ declare abstract class Auth {
224
266
  * @param audience - The venue's DID, supplied by the transport. Providers
225
267
  * that bind tokens to the venue's identity (e.g. {@link Ed25519Auth}) use it
226
268
  * as the JWT `aud`; others ignore it.
269
+ * @returns Nothing, or a promise for providers that sign asynchronously
270
+ * (e.g. {@link Ed25519Auth.fromSigner} over a WebCrypto key). The transport
271
+ * awaits it before sending, so callers of `apply` must await it too.
227
272
  */
228
- abstract apply(headers: Record<string, string>, audience?: string): void;
273
+ abstract apply(headers: Record<string, string>, audience?: string): void | Promise<void>;
229
274
  }
230
275
  /** No-op authentication provider. Sends no credentials. */
231
276
  declare class NoAuth extends Auth {
@@ -262,23 +307,34 @@ declare class BasicAuth extends Auth {
262
307
  * client's Ed25519 private key. The server verifies the signature and
263
308
  * extracts the caller's DID from the `sub` claim.
264
309
  *
310
+ * Construct it from a raw 32-byte key, or with {@link Ed25519Auth.fromSigner}
311
+ * from an {@link Ed25519Signer} — e.g. a non-extractable WebCrypto key, which
312
+ * signs without the key ever being readable by page scripts. Signer-backed
313
+ * instances sign asynchronously; the SDK transport awaits them.
314
+ *
265
315
  * Example:
266
316
  * const auth = Ed25519Auth.generate();
267
317
  * console.log(auth.getDID()); // did:key:z6Mk...
268
318
  * const venue = await Grid.connect("https://your-venue.example.com", auth);
319
+ *
320
+ * // Non-extractable key (browser):
321
+ * const signer = await webCryptoSigner(await generateNonExtractableKeyPair());
322
+ * const venue2 = await Grid.connect("https://your-venue.example.com", Ed25519Auth.fromSigner(signer));
269
323
  */
270
324
  declare class Ed25519Auth extends Auth {
271
- private _privateKey;
325
+ /** Present only for raw-key instances; signer-backed ones never see key bytes. */
326
+ private _privateKey?;
327
+ private _signer;
272
328
  private _publicKey;
273
329
  private _did;
274
330
  private _lifetime;
275
331
  private _audience?;
276
332
  /**
277
- * @param privateKey - 32-byte Ed25519 private key
333
+ * @param key - 32-byte Ed25519 private key, or an {@link Ed25519Signer}
278
334
  * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
279
335
  */
280
- constructor(privateKey: Uint8Array, tokenLifetimeSeconds?: number);
281
- apply(headers: Record<string, string>, audience?: string): void;
336
+ constructor(key: Uint8Array | Ed25519Signer, tokenLifetimeSeconds?: number);
337
+ apply(headers: Record<string, string>, audience?: string): void | Promise<void>;
282
338
  /**
283
339
  * Mint a bearer-usable identity JWT for this key — the same token
284
340
  * {@link apply} attaches to every request, exposed for callers that need
@@ -290,10 +346,19 @@ declare class Ed25519Auth extends Auth {
290
346
  * at any venue that accepts the caller's DID, so minting one is refused
291
347
  * rather than silently weakened.
292
348
  *
349
+ * Raw-key instances only: a signer-backed instance signs asynchronously,
350
+ * so use {@link mintIdentityToken}, which works for both.
351
+ *
293
352
  * @param audience - The venue DID the token is bound to (`aud` claim).
294
353
  * @param lifetimeSeconds - Token lifetime; defaults to this instance's.
295
354
  */
296
355
  identityToken(audience?: string, lifetimeSeconds?: number): string;
356
+ /**
357
+ * Async {@link identityToken} that works for raw-key and signer-backed
358
+ * instances alike. Same token, same audience rules.
359
+ */
360
+ mintIdentityToken(audience?: string, lifetimeSeconds?: number): Promise<string>;
361
+ private resolveAudience;
297
362
  /** The caller's DID derived from the public key. */
298
363
  getDID(): string;
299
364
  /**
@@ -308,6 +373,11 @@ declare class Ed25519Auth extends Auth {
308
373
  static generate(tokenLifetimeSeconds?: number): Ed25519Auth;
309
374
  /** Create from a hex-encoded private key string. */
310
375
  static fromHex(privateKeyHex: string, tokenLifetimeSeconds?: number): Ed25519Auth;
376
+ /**
377
+ * Create from an {@link Ed25519Signer}, e.g. `await webCryptoSigner(keyPair)`
378
+ * over a non-extractable WebCrypto key. Requests sign asynchronously.
379
+ */
380
+ static fromSigner(signer: Ed25519Signer, tokenLifetimeSeconds?: number): Ed25519Auth;
311
381
  }
312
382
  /**
313
383
  * @deprecated Renamed to {@link Ed25519Auth} for cross-SDK consistency
@@ -367,7 +437,7 @@ interface VenueRequestContext {
367
437
  baseUrl: string;
368
438
  venueId: string;
369
439
  auth: {
370
- apply(headers: Record<string, string>, audience?: string): void;
440
+ apply(headers: Record<string, string>, audience?: string): void | Promise<void>;
371
441
  };
372
442
  }
373
443
 
@@ -2677,6 +2747,7 @@ declare function didFromPublicKey(publicKey: Uint8Array): string;
2677
2747
  * `ucans` request array and relayed across cross-venue hops. Delegation chains
2678
2748
  * embed parent tokens as JWT strings in `prf`.
2679
2749
  */
2750
+
2680
2751
  /** The ability that instructs a venue to relay a cross-venue hop as itself. */
2681
2752
  declare const VENUE_RELAY = "venue/relay";
2682
2753
  interface UCANCapability {
@@ -2700,6 +2771,11 @@ declare function didFor(privateKey: Uint8Array): string;
2700
2771
  * @param proofs parent UCAN JWT strings (`prf`) for delegation chains
2701
2772
  */
2702
2773
  declare function createUCANJWT(privateKey: Uint8Array, audienceDID: string, att: UCANCapability[], lifetimeSeconds: number | null, proofs?: string[]): string;
2774
+ /**
2775
+ * {@link createUCANJWT} through an {@link Ed25519Signer}, for issuers whose
2776
+ * key is not readable bytes (e.g. a non-extractable WebCrypto key). Same token.
2777
+ */
2778
+ declare function createUCANJWTWith(signer: Ed25519Signer, audienceDID: string, att: UCANCapability[], lifetimeSeconds: number | null, proofs?: string[]): Promise<string>;
2703
2779
  /**
2704
2780
  * Mint an **identity token**: a UCAN with an EMPTY attenuation list, audienced
2705
2781
  * to `venueDID`. Pure proof of identity — it grants nothing, and being
@@ -2716,6 +2792,8 @@ declare function identityToken(privateKey: Uint8Array, venueDID: string, lifetim
2716
2792
  * in issuance.
2717
2793
  */
2718
2794
  declare function grant(ownerPrivateKey: Uint8Array, audienceDID: string, withResource: string, can: string, lifetimeSeconds: number): string;
2795
+ /** {@link grant} through an {@link Ed25519Signer}. */
2796
+ declare function grantWith(ownerSigner: Ed25519Signer, audienceDID: string, withResource: string, can: string, lifetimeSeconds: number): Promise<string>;
2719
2797
  /**
2720
2798
  * Mint a **relay delegation**: instructs and authorises `venueDID` to make a
2721
2799
  * cross-venue hop authenticated as itself, exercising the caller's authority.
@@ -2724,5 +2802,7 @@ declare function grant(ownerPrivateKey: Uint8Array, audienceDID: string, withRes
2724
2802
  * authenticated caller (COG-15).
2725
2803
  */
2726
2804
  declare function relayDelegation(privateKey: Uint8Array, venueDID: string, lifetimeSeconds: number, caps?: UCANCapability[]): string;
2805
+ /** {@link relayDelegation} through an {@link Ed25519Signer}. */
2806
+ declare function relayDelegationWith(signer: Ed25519Signer, venueDID: string, lifetimeSeconds: number, caps?: UCANCapability[]): Promise<string>;
2727
2807
 
2728
- export { type A2AAuthRef, type A2AImportAgentInput, type A2AImportAgentResult, A2AManager, type A2AMessage, type A2APart, type A2ATask, type AdapterInfo, AdapterManager, type AdaptersResult, Agent, type AgentCancelTaskInput, type AgentCard, type AgentChatInput, type AgentChatResult, type AgentCompactedSegment, type AgentCompleteTaskResult, type AgentContextInput, type AgentCreateInput, type AgentCreateResult, type AgentCycleEndEvent, type AgentCycleStartEvent, type AgentDeleteInput, type AgentDeleteResult, type AgentEvent, type AgentEventEnvelope, type AgentFailTaskResult, type AgentForkInput, type AgentForkResult, type AgentInferenceEndEvent, type AgentInferenceStartEvent, type AgentInfoResult, type AgentListInput, type AgentListResult, AgentManager, type AgentMessageInput, type AgentMessageResult, type AgentRenameSessionResult, type AgentRequestInput, type AgentRequestResult, type AgentResumeInput, type AgentRunEndEvent, type AgentRunStartEvent, type AgentSession, type AgentSessionListOptions, type AgentSessionMessage, type AgentSessionMetadata, AgentSessionNotFoundError, type AgentSessionPage, type AgentSessionRole, AgentStatus, type AgentStatusEvent, type AgentSuspendResult, type AgentToolResultEvent, type AgentToolStartEvent, type AgentTriggerInput, type AgentTriggerResult, type AgentUpdateInput, Asset, type AssetID, type AssetList, type AssetListItem, type AssetListOptions, AssetManager, type AssetMetadata, type AssetMetadataStore, AssetNotFoundError, type AssetPinResult, type AssetSummary, Auth, type AuthenticationKeyEntry, type AuthenticationKeysMap, type AuthenticationKeysResult, type AuthenticatorRevokeResult, BasicAuth, BearerAuth, ChatSession, type ConnectionAttempt, type ContentDetails, type ContentHashResult, CoviaConnectionError, type CoviaConnectionErrorOptions, CoviaError, CoviaTimeoutError, type Credentials, CredentialsHTTP, type DIDDocument, type DIDURL, type DLFSDrivesResult, type DLFSEntry, type DLFSListResult, DLFSManager, DataAsset, Ed25519Auth, type ExecutionScope, type ExpandedAssetList, type FunctionInfo, type FunctionsResult, Grid, GridError, type GroupCount, type InvokeOptions, type InvokePayload, Job, JobFailedError, type JobHistoryOptions, type JobHistoryPage, JobManager, type JobMetadata, JobNotFoundError, JobStatus, KeyPairAuth, type MCPContent, type MCPDiscovery, MCPError, MCPManager, type MCPTool, type MCPToolPage, type MCPToolResult, type MemoryChange, type MemoryEntry, MemoryManager, type MyAssetList, Namespace, NoAuth, NotFoundError, Operation, type OperationDetails, type OperationInfo, OperationManager, type OperationPayload, type OperationRunner, RateLimitError, RunStatus, type SSEEvent, ScopedWorkspace, type SecretExtractInput, type SecretExtractResult, SecretManager, type SecretSetInput, type SecretSetResult, type Skill, type SkillFacet, SkillManager, type SkillMetadata, type StatsData, type StatusData, type UCANAttenuation, type UCANCapability, type UCANIssueInput, type UCANIssueResult, UCANManager, type UCANVerifyResult, UnsupportedVenueFeatureError, type UserInfo, type UserListResult, UserManager, type UserSummary, VENUE_RELAY, Venue, type VenueConstructor, type VenueData, VenueIdentityChangedError, type VenueInterface, type VenueOptions, type WorkspaceAggregateResult, type WorkspaceAppendInput, type WorkspaceAppendResult, type WorkspaceCopyResult, type WorkspaceCountResult, type WorkspaceDeleteInput, type WorkspaceDeleteResult, type WorkspaceFieldValue, type WorkspaceInspectInput, type WorkspaceInspectResult, type WorkspaceListInput, type WorkspaceListResult, WorkspaceManager, type WorkspaceProjectedList, type WorkspaceReadInput, type WorkspaceReadResult, type WorkspaceSliceInput, type WorkspaceSliceResult, type WorkspaceWriteInput, type WorkspaceWriteResult, assetHash, createSSEEvent, createUCANJWT, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, hexToPrivateKey, identityToken, isDid, isJobComplete, isJobFinished, isJobPaused, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, relayDelegation, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates };
2808
+ export { type A2AAuthRef, type A2AImportAgentInput, type A2AImportAgentResult, A2AManager, type A2AMessage, type A2APart, type A2ATask, type AdapterInfo, AdapterManager, type AdaptersResult, Agent, type AgentCancelTaskInput, type AgentCard, type AgentChatInput, type AgentChatResult, type AgentCompactedSegment, type AgentCompleteTaskResult, type AgentContextInput, type AgentCreateInput, type AgentCreateResult, type AgentCycleEndEvent, type AgentCycleStartEvent, type AgentDeleteInput, type AgentDeleteResult, type AgentEvent, type AgentEventEnvelope, type AgentFailTaskResult, type AgentForkInput, type AgentForkResult, type AgentInferenceEndEvent, type AgentInferenceStartEvent, type AgentInfoResult, type AgentListInput, type AgentListResult, AgentManager, type AgentMessageInput, type AgentMessageResult, type AgentRenameSessionResult, type AgentRequestInput, type AgentRequestResult, type AgentResumeInput, type AgentRunEndEvent, type AgentRunStartEvent, type AgentSession, type AgentSessionListOptions, type AgentSessionMessage, type AgentSessionMetadata, AgentSessionNotFoundError, type AgentSessionPage, type AgentSessionRole, AgentStatus, type AgentStatusEvent, type AgentSuspendResult, type AgentToolResultEvent, type AgentToolStartEvent, type AgentTriggerInput, type AgentTriggerResult, type AgentUpdateInput, Asset, type AssetID, type AssetList, type AssetListItem, type AssetListOptions, AssetManager, type AssetMetadata, type AssetMetadataStore, AssetNotFoundError, type AssetPinResult, type AssetSummary, Auth, type AuthenticationKeyEntry, type AuthenticationKeysMap, type AuthenticationKeysResult, type AuthenticatorRevokeResult, BasicAuth, BearerAuth, ChatSession, type ConnectionAttempt, type ContentDetails, type ContentHashResult, CoviaConnectionError, type CoviaConnectionErrorOptions, CoviaError, CoviaTimeoutError, type Credentials, CredentialsHTTP, type DIDDocument, type DIDURL, type DLFSDrivesResult, type DLFSEntry, type DLFSListResult, DLFSManager, DataAsset, Ed25519Auth, type Ed25519Signer, type ExecutionScope, type ExpandedAssetList, type FunctionInfo, type FunctionsResult, Grid, GridError, type GroupCount, type InvokeOptions, type InvokePayload, Job, JobFailedError, type JobHistoryOptions, type JobHistoryPage, JobManager, type JobMetadata, JobNotFoundError, JobStatus, KeyPairAuth, type MCPContent, type MCPDiscovery, MCPError, MCPManager, type MCPTool, type MCPToolPage, type MCPToolResult, type MemoryChange, type MemoryEntry, MemoryManager, type MyAssetList, Namespace, NoAuth, NotFoundError, Operation, type OperationDetails, type OperationInfo, OperationManager, type OperationPayload, type OperationRunner, RateLimitError, RunStatus, type SSEEvent, ScopedWorkspace, type SecretExtractInput, type SecretExtractResult, SecretManager, type SecretSetInput, type SecretSetResult, type Skill, type SkillFacet, SkillManager, type SkillMetadata, type StatsData, type StatusData, type UCANAttenuation, type UCANCapability, type UCANIssueInput, type UCANIssueResult, UCANManager, type UCANVerifyResult, UnsupportedVenueFeatureError, type UserInfo, type UserListResult, UserManager, type UserSummary, VENUE_RELAY, Venue, type VenueConstructor, type VenueData, VenueIdentityChangedError, type VenueInterface, type VenueOptions, type WorkspaceAggregateResult, type WorkspaceAppendInput, type WorkspaceAppendResult, type WorkspaceCopyResult, type WorkspaceCountResult, type WorkspaceDeleteInput, type WorkspaceDeleteResult, type WorkspaceFieldValue, type WorkspaceInspectInput, type WorkspaceInspectResult, type WorkspaceListInput, type WorkspaceListResult, WorkspaceManager, type WorkspaceProjectedList, type WorkspaceReadInput, type WorkspaceReadResult, type WorkspaceSliceInput, type WorkspaceSliceResult, type WorkspaceWriteInput, type WorkspaceWriteResult, assetHash, createSSEEvent, createUCANJWT, createUCANJWTWith, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, generateNonExtractableKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, grantWith, hexToPrivateKey, identityToken, importNonExtractableKey, isDid, isJobComplete, isJobFinished, isJobPaused, isWebCryptoEd25519Supported, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, rawKeySigner, relayDelegation, relayDelegationWith, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates, webCryptoSigner };
package/dist/index.js CHANGED
@@ -165,15 +165,15 @@ var isBig = (n) => typeof n === "bigint";
165
165
  var isStr = (s) => typeof s === "string";
166
166
  var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
167
167
  var abytes = (value, length, title = "") => {
168
- const bytes = isBytes(value);
168
+ const bytes2 = isBytes(value);
169
169
  const len = value?.length;
170
170
  const needsLen = length !== void 0;
171
- if (!bytes || needsLen && len !== length) {
171
+ if (!bytes2 || needsLen && len !== length) {
172
172
  const prefix = title && `"${title}" `;
173
173
  const ofLen = needsLen ? ` of length ${length}` : "";
174
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
174
+ const got = bytes2 ? `length=${len}` : `type=${typeof value}`;
175
175
  const msg = prefix + "expected Uint8Array" + ofLen + ", got " + got;
176
- throw bytes ? new RangeError(msg) : new TypeError(msg);
176
+ throw bytes2 ? new RangeError(msg) : new TypeError(msg);
177
177
  }
178
178
  return value;
179
179
  };
@@ -632,15 +632,15 @@ function isBytes2(a) {
632
632
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
633
633
  }
634
634
  function abytes2(value, length, title = "") {
635
- const bytes = isBytes2(value);
635
+ const bytes2 = isBytes2(value);
636
636
  const len = value?.length;
637
637
  const needsLen = length !== void 0;
638
- if (!bytes || needsLen) {
638
+ if (!bytes2 || needsLen) {
639
639
  const prefix = title && `"${title}" `;
640
640
  const ofLen = "";
641
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
641
+ const got = bytes2 ? `length=${len}` : `type=${typeof value}`;
642
642
  const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
643
- if (!bytes)
643
+ if (!bytes2)
644
644
  throw new TypeError(message);
645
645
  throw new RangeError(message);
646
646
  }
@@ -1061,11 +1061,11 @@ function hexToPrivateKey(hex) {
1061
1061
  if (!/^[0-9a-fA-F]{64}$/.test(cleaned)) {
1062
1062
  throw new Error("Invalid Ed25519 private key: expected 64 hex characters (32 bytes)");
1063
1063
  }
1064
- const bytes = new Uint8Array(32);
1065
- for (let i = 0; i < bytes.length; i++) {
1066
- bytes[i] = parseInt(cleaned.substring(i * 2, i * 2 + 2), 16);
1064
+ const bytes2 = new Uint8Array(32);
1065
+ for (let i = 0; i < bytes2.length; i++) {
1066
+ bytes2[i] = parseInt(cleaned.substring(i * 2, i * 2 + 2), 16);
1067
1067
  }
1068
- return bytes;
1068
+ return bytes2;
1069
1069
  }
1070
1070
 
1071
1071
  // src/crypto/base58.ts
@@ -1075,13 +1075,13 @@ var ALPHABET_MAP = /* @__PURE__ */ new Map();
1075
1075
  for (let i = 0; i < ALPHABET.length; i++) {
1076
1076
  ALPHABET_MAP.set(ALPHABET[i], i);
1077
1077
  }
1078
- function encode(bytes) {
1079
- if (bytes.length === 0) return "";
1078
+ function encode(bytes2) {
1079
+ if (bytes2.length === 0) return "";
1080
1080
  let zeros = 0;
1081
- while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
1081
+ while (zeros < bytes2.length && bytes2[zeros] === 0) zeros++;
1082
1082
  const digits = [];
1083
- for (let i = zeros; i < bytes.length; i++) {
1084
- let carry = bytes[i];
1083
+ for (let i = zeros; i < bytes2.length; i++) {
1084
+ let carry = bytes2[i];
1085
1085
  for (let j = 0; j < digits.length; j++) {
1086
1086
  carry += digits[j] << 8;
1087
1087
  digits[j] = carry % BASE;
@@ -1102,24 +1102,24 @@ function decode(str) {
1102
1102
  if (str.length === 0) return new Uint8Array(0);
1103
1103
  let zeros = 0;
1104
1104
  while (zeros < str.length && str[zeros] === ALPHABET[0]) zeros++;
1105
- const bytes = [];
1105
+ const bytes2 = [];
1106
1106
  for (let i = zeros; i < str.length; i++) {
1107
1107
  const val = ALPHABET_MAP.get(str[i]);
1108
1108
  if (val === void 0) throw new Error(`Invalid base58 character: ${str[i]}`);
1109
1109
  let carry = val;
1110
- for (let j = 0; j < bytes.length; j++) {
1111
- carry += bytes[j] * BASE;
1112
- bytes[j] = carry & 255;
1110
+ for (let j = 0; j < bytes2.length; j++) {
1111
+ carry += bytes2[j] * BASE;
1112
+ bytes2[j] = carry & 255;
1113
1113
  carry >>= 8;
1114
1114
  }
1115
1115
  while (carry > 0) {
1116
- bytes.push(carry & 255);
1116
+ bytes2.push(carry & 255);
1117
1117
  carry >>= 8;
1118
1118
  }
1119
1119
  }
1120
- const result = new Uint8Array(zeros + bytes.length);
1120
+ const result = new Uint8Array(zeros + bytes2.length);
1121
1121
  for (let i = 0; i < zeros; i++) result[i] = 0;
1122
- for (let i = 0; i < bytes.length; i++) result[zeros + i] = bytes[bytes.length - 1 - i];
1122
+ for (let i = 0; i < bytes2.length; i++) result[zeros + i] = bytes2[bytes2.length - 1 - i];
1123
1123
  return result;
1124
1124
  }
1125
1125
 
@@ -1155,7 +1155,16 @@ function base64UrlEncode(data) {
1155
1155
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1156
1156
  }
1157
1157
  function createEdDSAJWT(privateKey, lifetimeSeconds = 300, audience) {
1158
- const publicKey = getPublicKey2(privateKey);
1158
+ const signingInput = edDSASigningInput(getPublicKey2(privateKey), lifetimeSeconds, audience);
1159
+ const signature = sign(encoder.encode(signingInput), privateKey);
1160
+ return `${signingInput}.${base64UrlEncode(signature)}`;
1161
+ }
1162
+ async function createEdDSAJWTWith(signer, lifetimeSeconds = 300, audience) {
1163
+ const signingInput = edDSASigningInput(signer.publicKey, lifetimeSeconds, audience);
1164
+ const signature = await signer.sign(encoder.encode(signingInput));
1165
+ return `${signingInput}.${base64UrlEncode(signature)}`;
1166
+ }
1167
+ function edDSASigningInput(publicKey, lifetimeSeconds, audience) {
1159
1168
  const multikey = encodePublicKey(publicKey);
1160
1169
  const did = `did:key:${multikey}`;
1161
1170
  const nowSecs = Math.floor(Date.now() / 1e3);
@@ -1173,18 +1182,95 @@ function createEdDSAJWT(privateKey, lifetimeSeconds = 300, audience) {
1173
1182
  const payload = JSON.stringify(claims);
1174
1183
  const headerB64 = base64UrlEncode(encoder.encode(header));
1175
1184
  const payloadB64 = base64UrlEncode(encoder.encode(payload));
1176
- const signingInput = `${headerB64}.${payloadB64}`;
1177
- const signature = sign(encoder.encode(signingInput), privateKey);
1178
- const signatureB64 = base64UrlEncode(signature);
1179
- return `${signingInput}.${signatureB64}`;
1185
+ return `${headerB64}.${payloadB64}`;
1186
+ }
1187
+
1188
+ // src/crypto/signer.ts
1189
+ var ED25519 = "Ed25519";
1190
+ var PKCS8_ED25519_PREFIX = new Uint8Array([
1191
+ 48,
1192
+ 46,
1193
+ 2,
1194
+ 1,
1195
+ 0,
1196
+ 48,
1197
+ 5,
1198
+ 6,
1199
+ 3,
1200
+ 43,
1201
+ 101,
1202
+ 112,
1203
+ 4,
1204
+ 34,
1205
+ 4,
1206
+ 32
1207
+ ]);
1208
+ function subtle2() {
1209
+ const s = globalThis.crypto?.subtle;
1210
+ if (!s) {
1211
+ throw new Error("WebCrypto is unavailable: crypto.subtle requires a secure context (HTTPS or localhost)");
1212
+ }
1213
+ return s;
1214
+ }
1215
+ function bytes(data) {
1216
+ return new Uint8Array(data);
1217
+ }
1218
+ function rawKeySigner(privateKey) {
1219
+ const publicKey = getPublicKey2(privateKey);
1220
+ return {
1221
+ publicKey,
1222
+ sign: (data) => Promise.resolve(sign(data, privateKey))
1223
+ };
1224
+ }
1225
+ async function webCryptoSigner(keyPair) {
1226
+ const publicKey = new Uint8Array(await subtle2().exportKey("raw", keyPair.publicKey));
1227
+ const privateKey = keyPair.privateKey;
1228
+ return {
1229
+ publicKey,
1230
+ sign: async (data) => new Uint8Array(await subtle2().sign(ED25519, privateKey, bytes(data)))
1231
+ };
1232
+ }
1233
+ async function generateNonExtractableKeyPair() {
1234
+ return subtle2().generateKey(ED25519, false, ["sign", "verify"]);
1235
+ }
1236
+ async function importNonExtractableKey(privateKey) {
1237
+ if (privateKey.length !== 32) {
1238
+ throw new Error("Invalid Ed25519 private key: expected 32 bytes");
1239
+ }
1240
+ const pkcs8 = new Uint8Array(PKCS8_ED25519_PREFIX.length + 32);
1241
+ pkcs8.set(PKCS8_ED25519_PREFIX, 0);
1242
+ pkcs8.set(privateKey, PKCS8_ED25519_PREFIX.length);
1243
+ try {
1244
+ const s = subtle2();
1245
+ const [priv, pub] = await Promise.all([
1246
+ s.importKey("pkcs8", pkcs8, ED25519, false, ["sign"]),
1247
+ s.importKey("raw", bytes(getPublicKey2(privateKey)), ED25519, true, ["verify"])
1248
+ ]);
1249
+ return { privateKey: priv, publicKey: pub };
1250
+ } finally {
1251
+ pkcs8.fill(0);
1252
+ }
1253
+ }
1254
+ var supported;
1255
+ function isWebCryptoEd25519Supported() {
1256
+ supported ?? (supported = (async () => {
1257
+ try {
1258
+ const kp = await generateNonExtractableKeyPair();
1259
+ await subtle2().sign(ED25519, kp.privateKey, new Uint8Array(1));
1260
+ return true;
1261
+ } catch {
1262
+ return false;
1263
+ }
1264
+ })());
1265
+ return supported;
1180
1266
  }
1181
1267
 
1182
1268
  // src/Credentials.ts
1183
1269
  function base64Encode(text) {
1184
- const bytes = new TextEncoder().encode(text);
1270
+ const bytes2 = new TextEncoder().encode(text);
1185
1271
  let binary = "";
1186
- for (let i = 0; i < bytes.length; i++) {
1187
- binary += String.fromCharCode(bytes[i]);
1272
+ for (let i = 0; i < bytes2.length; i++) {
1273
+ binary += String.fromCharCode(bytes2[i]);
1188
1274
  }
1189
1275
  return btoa(binary);
1190
1276
  }
@@ -1216,18 +1302,29 @@ var BasicAuth = class extends Auth {
1216
1302
  };
1217
1303
  var Ed25519Auth = class _Ed25519Auth extends Auth {
1218
1304
  /**
1219
- * @param privateKey - 32-byte Ed25519 private key
1305
+ * @param key - 32-byte Ed25519 private key, or an {@link Ed25519Signer}
1220
1306
  * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
1221
1307
  */
1222
- constructor(privateKey, tokenLifetimeSeconds = 300) {
1308
+ constructor(key, tokenLifetimeSeconds = 300) {
1223
1309
  super();
1224
- this._privateKey = privateKey;
1225
- this._publicKey = getPublicKey2(privateKey);
1310
+ if (isSigner(key)) {
1311
+ this._signer = key;
1312
+ } else {
1313
+ this._privateKey = key;
1314
+ this._signer = rawKeySigner(key);
1315
+ }
1316
+ this._publicKey = this._signer.publicKey;
1226
1317
  this._did = didFromPublicKey(this._publicKey);
1227
1318
  this._lifetime = tokenLifetimeSeconds;
1228
1319
  }
1229
1320
  apply(headers, audience) {
1230
- headers["Authorization"] = `Bearer ${this.identityToken(audience)}`;
1321
+ if (this._privateKey) {
1322
+ headers["Authorization"] = `Bearer ${this.identityToken(audience)}`;
1323
+ return;
1324
+ }
1325
+ return this.mintIdentityToken(audience).then((token) => {
1326
+ headers["Authorization"] = `Bearer ${token}`;
1327
+ });
1231
1328
  }
1232
1329
  /**
1233
1330
  * Mint a bearer-usable identity JWT for this key — the same token
@@ -1240,17 +1337,37 @@ var Ed25519Auth = class _Ed25519Auth extends Auth {
1240
1337
  * at any venue that accepts the caller's DID, so minting one is refused
1241
1338
  * rather than silently weakened.
1242
1339
  *
1340
+ * Raw-key instances only: a signer-backed instance signs asynchronously,
1341
+ * so use {@link mintIdentityToken}, which works for both.
1342
+ *
1243
1343
  * @param audience - The venue DID the token is bound to (`aud` claim).
1244
1344
  * @param lifetimeSeconds - Token lifetime; defaults to this instance's.
1245
1345
  */
1246
1346
  identityToken(audience, lifetimeSeconds) {
1347
+ const aud = this.resolveAudience(audience);
1348
+ if (!this._privateKey) {
1349
+ throw new CoviaError(
1350
+ "Ed25519Auth.identityToken() needs a raw private key; this instance signs through an Ed25519Signer, so use the async mintIdentityToken() instead."
1351
+ );
1352
+ }
1353
+ return createEdDSAJWT(this._privateKey, lifetimeSeconds ?? this._lifetime, aud);
1354
+ }
1355
+ /**
1356
+ * Async {@link identityToken} that works for raw-key and signer-backed
1357
+ * instances alike. Same token, same audience rules.
1358
+ */
1359
+ async mintIdentityToken(audience, lifetimeSeconds) {
1360
+ const aud = this.resolveAudience(audience);
1361
+ return createEdDSAJWTWith(this._signer, lifetimeSeconds ?? this._lifetime, aud);
1362
+ }
1363
+ resolveAudience(audience) {
1247
1364
  const aud = this._audience ?? (audience || void 0);
1248
1365
  if (!aud) {
1249
1366
  throw new CoviaError(
1250
1367
  "Ed25519Auth requires a venue audience to bind the token to: connect via Grid.connect()/Venue.connect() so the venue DID is known, or pin auth.audience explicitly."
1251
1368
  );
1252
1369
  }
1253
- return createEdDSAJWT(this._privateKey, lifetimeSeconds ?? this._lifetime, aud);
1370
+ return aud;
1254
1371
  }
1255
1372
  /** The caller's DID derived from the public key. */
1256
1373
  getDID() {
@@ -1279,7 +1396,17 @@ var Ed25519Auth = class _Ed25519Auth extends Auth {
1279
1396
  static fromHex(privateKeyHex, tokenLifetimeSeconds = 300) {
1280
1397
  return new _Ed25519Auth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
1281
1398
  }
1399
+ /**
1400
+ * Create from an {@link Ed25519Signer}, e.g. `await webCryptoSigner(keyPair)`
1401
+ * over a non-extractable WebCrypto key. Requests sign asynchronously.
1402
+ */
1403
+ static fromSigner(signer, tokenLifetimeSeconds = 300) {
1404
+ return new _Ed25519Auth(signer, tokenLifetimeSeconds);
1405
+ }
1282
1406
  };
1407
+ function isSigner(key) {
1408
+ return !ArrayBuffer.isView(key) && typeof key.sign === "function";
1409
+ }
1283
1410
  var KeyPairAuth = Ed25519Auth;
1284
1411
  var CredentialsHTTP = class {
1285
1412
  constructor(venueId, apiKey, userId) {
@@ -1703,7 +1830,7 @@ var AdapterManager = class {
1703
1830
  };
1704
1831
 
1705
1832
  // src/VenueTransport.ts
1706
- function requestOptions(venue, options) {
1833
+ async function requestOptions(venue, options) {
1707
1834
  const {
1708
1835
  contentType,
1709
1836
  headers: suppliedHeaders = {},
@@ -1714,19 +1841,19 @@ function requestOptions(venue, options) {
1714
1841
  if (effectiveContentType && headers["Content-Type"] === void 0) {
1715
1842
  headers["Content-Type"] = effectiveContentType;
1716
1843
  }
1717
- venue.auth.apply(headers, venue.venueId);
1844
+ await venue.auth.apply(headers, venue.venueId);
1718
1845
  return { ...request, headers };
1719
1846
  }
1720
- function venueJson(venue, path, options = {}) {
1847
+ async function venueJson(venue, path, options = {}) {
1721
1848
  return fetchWithError(
1722
1849
  `${venue.baseUrl}${path}`,
1723
- requestOptions(venue, options)
1850
+ await requestOptions(venue, options)
1724
1851
  );
1725
1852
  }
1726
- function venueStream(venue, path, options = {}) {
1853
+ async function venueStream(venue, path, options = {}) {
1727
1854
  return fetchStreamWithError(
1728
1855
  `${venue.baseUrl}${path}`,
1729
- requestOptions(venue, options)
1856
+ await requestOptions(venue, options)
1730
1857
  );
1731
1858
  }
1732
1859
 
@@ -4067,7 +4194,17 @@ function didFor(privateKey) {
4067
4194
  return `did:key:${encodePublicKey(getPublicKey2(privateKey))}`;
4068
4195
  }
4069
4196
  function createUCANJWT(privateKey, audienceDID, att, lifetimeSeconds, proofs = []) {
4070
- const multikey = encodePublicKey(getPublicKey2(privateKey));
4197
+ const signingInput = ucanSigningInput(getPublicKey2(privateKey), audienceDID, att, lifetimeSeconds, proofs);
4198
+ const signature = sign(encoder2.encode(signingInput), privateKey);
4199
+ return `${signingInput}.${base64UrlEncode(signature)}`;
4200
+ }
4201
+ async function createUCANJWTWith(signer, audienceDID, att, lifetimeSeconds, proofs = []) {
4202
+ const signingInput = ucanSigningInput(signer.publicKey, audienceDID, att, lifetimeSeconds, proofs);
4203
+ const signature = await signer.sign(encoder2.encode(signingInput));
4204
+ return `${signingInput}.${base64UrlEncode(signature)}`;
4205
+ }
4206
+ function ucanSigningInput(publicKey, audienceDID, att, lifetimeSeconds, proofs) {
4207
+ const multikey = encodePublicKey(publicKey);
4071
4208
  const nowSecs = Math.floor(Date.now() / 1e3);
4072
4209
  const header = JSON.stringify({ alg: "EdDSA", typ: "JWT", kid: multikey });
4073
4210
  const claims = {
@@ -4083,9 +4220,7 @@ function createUCANJWT(privateKey, audienceDID, att, lifetimeSeconds, proofs = [
4083
4220
  // CVMDouble the venue's UcanJwtValidator rejects outright (covia-sdk#46).
4084
4221
  exp: lifetimeSeconds === null ? null : Math.floor(nowSecs + lifetimeSeconds)
4085
4222
  };
4086
- const signingInput = `${base64UrlEncode(encoder2.encode(header))}.${base64UrlEncode(encoder2.encode(JSON.stringify(claims)))}`;
4087
- const signature = sign(encoder2.encode(signingInput), privateKey);
4088
- return `${signingInput}.${base64UrlEncode(signature)}`;
4223
+ return `${base64UrlEncode(encoder2.encode(header))}.${base64UrlEncode(encoder2.encode(JSON.stringify(claims)))}`;
4089
4224
  }
4090
4225
  function identityToken(privateKey, venueDID, lifetimeSeconds = 300) {
4091
4226
  return createUCANJWT(privateKey, venueDID, [], lifetimeSeconds);
@@ -4093,10 +4228,17 @@ function identityToken(privateKey, venueDID, lifetimeSeconds = 300) {
4093
4228
  function grant(ownerPrivateKey, audienceDID, withResource, can, lifetimeSeconds) {
4094
4229
  return createUCANJWT(ownerPrivateKey, audienceDID, [{ with: withResource, can }], lifetimeSeconds);
4095
4230
  }
4231
+ function grantWith(ownerSigner, audienceDID, withResource, can, lifetimeSeconds) {
4232
+ return createUCANJWTWith(ownerSigner, audienceDID, [{ with: withResource, can }], lifetimeSeconds);
4233
+ }
4096
4234
  function relayDelegation(privateKey, venueDID, lifetimeSeconds, caps = []) {
4097
4235
  const att = [{ with: didFor(privateKey), can: VENUE_RELAY }, ...caps];
4098
4236
  return createUCANJWT(privateKey, venueDID, att, lifetimeSeconds);
4099
4237
  }
4238
+ function relayDelegationWith(signer, venueDID, lifetimeSeconds, caps = []) {
4239
+ const att = [{ with: didFromPublicKey(signer.publicKey), can: VENUE_RELAY }, ...caps];
4240
+ return createUCANJWTWith(signer, venueDID, att, lifetimeSeconds);
4241
+ }
4100
4242
  /*! Bundled license information:
4101
4243
 
4102
4244
  @noble/ed25519/index.js:
@@ -4154,6 +4296,7 @@ exports.WorkspaceManager = WorkspaceManager;
4154
4296
  exports.assetHash = assetHash;
4155
4297
  exports.createSSEEvent = createSSEEvent;
4156
4298
  exports.createUCANJWT = createUCANJWT;
4299
+ exports.createUCANJWTWith = createUCANJWTWith;
4157
4300
  exports.decodePublicKey = decodePublicKey;
4158
4301
  exports.didFor = didFor;
4159
4302
  exports.didFromPublicKey = didFromPublicKey;
@@ -4163,23 +4306,30 @@ exports.encodePublicKey = encodePublicKey;
4163
4306
  exports.fetchStreamWithError = fetchStreamWithError;
4164
4307
  exports.fetchWithError = fetchWithError;
4165
4308
  exports.generateKeyPair = generateKeyPair;
4309
+ exports.generateNonExtractableKeyPair = generateNonExtractableKeyPair;
4166
4310
  exports.getAssetIdFromPath = getAssetIdFromPath;
4167
4311
  exports.getAssetIdFromVenueId = getAssetIdFromVenueId;
4168
4312
  exports.getAssetMetadataStore = getAssetMetadataStore;
4169
4313
  exports.getParsedAssetId = getParsedAssetId;
4170
4314
  exports.grant = grant;
4315
+ exports.grantWith = grantWith;
4171
4316
  exports.hexToPrivateKey = hexToPrivateKey;
4172
4317
  exports.identityToken = identityToken;
4318
+ exports.importNonExtractableKey = importNonExtractableKey;
4173
4319
  exports.isDid = isDid;
4174
4320
  exports.isJobComplete = isJobComplete;
4175
4321
  exports.isJobFinished = isJobFinished;
4176
4322
  exports.isJobPaused = isJobPaused;
4323
+ exports.isWebCryptoEd25519Supported = isWebCryptoEd25519Supported;
4177
4324
  exports.logger = logger;
4178
4325
  exports.parseDidUrl = parseDidUrl;
4179
4326
  exports.parseRetryAfterMs = parseRetryAfterMs;
4180
4327
  exports.parseSSEStream = parseSSEStream;
4181
4328
  exports.privateKeyToHex = privateKeyToHex;
4329
+ exports.rawKeySigner = rawKeySigner;
4182
4330
  exports.relayDelegation = relayDelegation;
4331
+ exports.relayDelegationWith = relayDelegationWith;
4183
4332
  exports.retryDelayMs = retryDelayMs;
4184
4333
  exports.setAssetMetadataStore = setAssetMetadataStore;
4185
4334
  exports.venueBaseUrlCandidates = venueBaseUrlCandidates;
4335
+ exports.webCryptoSigner = webCryptoSigner;
package/dist/index.mjs CHANGED
@@ -163,15 +163,15 @@ var isBig = (n) => typeof n === "bigint";
163
163
  var isStr = (s) => typeof s === "string";
164
164
  var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
165
165
  var abytes = (value, length, title = "") => {
166
- const bytes = isBytes(value);
166
+ const bytes2 = isBytes(value);
167
167
  const len = value?.length;
168
168
  const needsLen = length !== void 0;
169
- if (!bytes || needsLen && len !== length) {
169
+ if (!bytes2 || needsLen && len !== length) {
170
170
  const prefix = title && `"${title}" `;
171
171
  const ofLen = needsLen ? ` of length ${length}` : "";
172
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
172
+ const got = bytes2 ? `length=${len}` : `type=${typeof value}`;
173
173
  const msg = prefix + "expected Uint8Array" + ofLen + ", got " + got;
174
- throw bytes ? new RangeError(msg) : new TypeError(msg);
174
+ throw bytes2 ? new RangeError(msg) : new TypeError(msg);
175
175
  }
176
176
  return value;
177
177
  };
@@ -630,15 +630,15 @@ function isBytes2(a) {
630
630
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
631
631
  }
632
632
  function abytes2(value, length, title = "") {
633
- const bytes = isBytes2(value);
633
+ const bytes2 = isBytes2(value);
634
634
  const len = value?.length;
635
635
  const needsLen = length !== void 0;
636
- if (!bytes || needsLen) {
636
+ if (!bytes2 || needsLen) {
637
637
  const prefix = title && `"${title}" `;
638
638
  const ofLen = "";
639
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
639
+ const got = bytes2 ? `length=${len}` : `type=${typeof value}`;
640
640
  const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
641
- if (!bytes)
641
+ if (!bytes2)
642
642
  throw new TypeError(message);
643
643
  throw new RangeError(message);
644
644
  }
@@ -1059,11 +1059,11 @@ function hexToPrivateKey(hex) {
1059
1059
  if (!/^[0-9a-fA-F]{64}$/.test(cleaned)) {
1060
1060
  throw new Error("Invalid Ed25519 private key: expected 64 hex characters (32 bytes)");
1061
1061
  }
1062
- const bytes = new Uint8Array(32);
1063
- for (let i = 0; i < bytes.length; i++) {
1064
- bytes[i] = parseInt(cleaned.substring(i * 2, i * 2 + 2), 16);
1062
+ const bytes2 = new Uint8Array(32);
1063
+ for (let i = 0; i < bytes2.length; i++) {
1064
+ bytes2[i] = parseInt(cleaned.substring(i * 2, i * 2 + 2), 16);
1065
1065
  }
1066
- return bytes;
1066
+ return bytes2;
1067
1067
  }
1068
1068
 
1069
1069
  // src/crypto/base58.ts
@@ -1073,13 +1073,13 @@ var ALPHABET_MAP = /* @__PURE__ */ new Map();
1073
1073
  for (let i = 0; i < ALPHABET.length; i++) {
1074
1074
  ALPHABET_MAP.set(ALPHABET[i], i);
1075
1075
  }
1076
- function encode(bytes) {
1077
- if (bytes.length === 0) return "";
1076
+ function encode(bytes2) {
1077
+ if (bytes2.length === 0) return "";
1078
1078
  let zeros = 0;
1079
- while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
1079
+ while (zeros < bytes2.length && bytes2[zeros] === 0) zeros++;
1080
1080
  const digits = [];
1081
- for (let i = zeros; i < bytes.length; i++) {
1082
- let carry = bytes[i];
1081
+ for (let i = zeros; i < bytes2.length; i++) {
1082
+ let carry = bytes2[i];
1083
1083
  for (let j = 0; j < digits.length; j++) {
1084
1084
  carry += digits[j] << 8;
1085
1085
  digits[j] = carry % BASE;
@@ -1100,24 +1100,24 @@ function decode(str) {
1100
1100
  if (str.length === 0) return new Uint8Array(0);
1101
1101
  let zeros = 0;
1102
1102
  while (zeros < str.length && str[zeros] === ALPHABET[0]) zeros++;
1103
- const bytes = [];
1103
+ const bytes2 = [];
1104
1104
  for (let i = zeros; i < str.length; i++) {
1105
1105
  const val = ALPHABET_MAP.get(str[i]);
1106
1106
  if (val === void 0) throw new Error(`Invalid base58 character: ${str[i]}`);
1107
1107
  let carry = val;
1108
- for (let j = 0; j < bytes.length; j++) {
1109
- carry += bytes[j] * BASE;
1110
- bytes[j] = carry & 255;
1108
+ for (let j = 0; j < bytes2.length; j++) {
1109
+ carry += bytes2[j] * BASE;
1110
+ bytes2[j] = carry & 255;
1111
1111
  carry >>= 8;
1112
1112
  }
1113
1113
  while (carry > 0) {
1114
- bytes.push(carry & 255);
1114
+ bytes2.push(carry & 255);
1115
1115
  carry >>= 8;
1116
1116
  }
1117
1117
  }
1118
- const result = new Uint8Array(zeros + bytes.length);
1118
+ const result = new Uint8Array(zeros + bytes2.length);
1119
1119
  for (let i = 0; i < zeros; i++) result[i] = 0;
1120
- for (let i = 0; i < bytes.length; i++) result[zeros + i] = bytes[bytes.length - 1 - i];
1120
+ for (let i = 0; i < bytes2.length; i++) result[zeros + i] = bytes2[bytes2.length - 1 - i];
1121
1121
  return result;
1122
1122
  }
1123
1123
 
@@ -1153,7 +1153,16 @@ function base64UrlEncode(data) {
1153
1153
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1154
1154
  }
1155
1155
  function createEdDSAJWT(privateKey, lifetimeSeconds = 300, audience) {
1156
- const publicKey = getPublicKey2(privateKey);
1156
+ const signingInput = edDSASigningInput(getPublicKey2(privateKey), lifetimeSeconds, audience);
1157
+ const signature = sign(encoder.encode(signingInput), privateKey);
1158
+ return `${signingInput}.${base64UrlEncode(signature)}`;
1159
+ }
1160
+ async function createEdDSAJWTWith(signer, lifetimeSeconds = 300, audience) {
1161
+ const signingInput = edDSASigningInput(signer.publicKey, lifetimeSeconds, audience);
1162
+ const signature = await signer.sign(encoder.encode(signingInput));
1163
+ return `${signingInput}.${base64UrlEncode(signature)}`;
1164
+ }
1165
+ function edDSASigningInput(publicKey, lifetimeSeconds, audience) {
1157
1166
  const multikey = encodePublicKey(publicKey);
1158
1167
  const did = `did:key:${multikey}`;
1159
1168
  const nowSecs = Math.floor(Date.now() / 1e3);
@@ -1171,18 +1180,95 @@ function createEdDSAJWT(privateKey, lifetimeSeconds = 300, audience) {
1171
1180
  const payload = JSON.stringify(claims);
1172
1181
  const headerB64 = base64UrlEncode(encoder.encode(header));
1173
1182
  const payloadB64 = base64UrlEncode(encoder.encode(payload));
1174
- const signingInput = `${headerB64}.${payloadB64}`;
1175
- const signature = sign(encoder.encode(signingInput), privateKey);
1176
- const signatureB64 = base64UrlEncode(signature);
1177
- return `${signingInput}.${signatureB64}`;
1183
+ return `${headerB64}.${payloadB64}`;
1184
+ }
1185
+
1186
+ // src/crypto/signer.ts
1187
+ var ED25519 = "Ed25519";
1188
+ var PKCS8_ED25519_PREFIX = new Uint8Array([
1189
+ 48,
1190
+ 46,
1191
+ 2,
1192
+ 1,
1193
+ 0,
1194
+ 48,
1195
+ 5,
1196
+ 6,
1197
+ 3,
1198
+ 43,
1199
+ 101,
1200
+ 112,
1201
+ 4,
1202
+ 34,
1203
+ 4,
1204
+ 32
1205
+ ]);
1206
+ function subtle2() {
1207
+ const s = globalThis.crypto?.subtle;
1208
+ if (!s) {
1209
+ throw new Error("WebCrypto is unavailable: crypto.subtle requires a secure context (HTTPS or localhost)");
1210
+ }
1211
+ return s;
1212
+ }
1213
+ function bytes(data) {
1214
+ return new Uint8Array(data);
1215
+ }
1216
+ function rawKeySigner(privateKey) {
1217
+ const publicKey = getPublicKey2(privateKey);
1218
+ return {
1219
+ publicKey,
1220
+ sign: (data) => Promise.resolve(sign(data, privateKey))
1221
+ };
1222
+ }
1223
+ async function webCryptoSigner(keyPair) {
1224
+ const publicKey = new Uint8Array(await subtle2().exportKey("raw", keyPair.publicKey));
1225
+ const privateKey = keyPair.privateKey;
1226
+ return {
1227
+ publicKey,
1228
+ sign: async (data) => new Uint8Array(await subtle2().sign(ED25519, privateKey, bytes(data)))
1229
+ };
1230
+ }
1231
+ async function generateNonExtractableKeyPair() {
1232
+ return subtle2().generateKey(ED25519, false, ["sign", "verify"]);
1233
+ }
1234
+ async function importNonExtractableKey(privateKey) {
1235
+ if (privateKey.length !== 32) {
1236
+ throw new Error("Invalid Ed25519 private key: expected 32 bytes");
1237
+ }
1238
+ const pkcs8 = new Uint8Array(PKCS8_ED25519_PREFIX.length + 32);
1239
+ pkcs8.set(PKCS8_ED25519_PREFIX, 0);
1240
+ pkcs8.set(privateKey, PKCS8_ED25519_PREFIX.length);
1241
+ try {
1242
+ const s = subtle2();
1243
+ const [priv, pub] = await Promise.all([
1244
+ s.importKey("pkcs8", pkcs8, ED25519, false, ["sign"]),
1245
+ s.importKey("raw", bytes(getPublicKey2(privateKey)), ED25519, true, ["verify"])
1246
+ ]);
1247
+ return { privateKey: priv, publicKey: pub };
1248
+ } finally {
1249
+ pkcs8.fill(0);
1250
+ }
1251
+ }
1252
+ var supported;
1253
+ function isWebCryptoEd25519Supported() {
1254
+ supported ?? (supported = (async () => {
1255
+ try {
1256
+ const kp = await generateNonExtractableKeyPair();
1257
+ await subtle2().sign(ED25519, kp.privateKey, new Uint8Array(1));
1258
+ return true;
1259
+ } catch {
1260
+ return false;
1261
+ }
1262
+ })());
1263
+ return supported;
1178
1264
  }
1179
1265
 
1180
1266
  // src/Credentials.ts
1181
1267
  function base64Encode(text) {
1182
- const bytes = new TextEncoder().encode(text);
1268
+ const bytes2 = new TextEncoder().encode(text);
1183
1269
  let binary = "";
1184
- for (let i = 0; i < bytes.length; i++) {
1185
- binary += String.fromCharCode(bytes[i]);
1270
+ for (let i = 0; i < bytes2.length; i++) {
1271
+ binary += String.fromCharCode(bytes2[i]);
1186
1272
  }
1187
1273
  return btoa(binary);
1188
1274
  }
@@ -1214,18 +1300,29 @@ var BasicAuth = class extends Auth {
1214
1300
  };
1215
1301
  var Ed25519Auth = class _Ed25519Auth extends Auth {
1216
1302
  /**
1217
- * @param privateKey - 32-byte Ed25519 private key
1303
+ * @param key - 32-byte Ed25519 private key, or an {@link Ed25519Signer}
1218
1304
  * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
1219
1305
  */
1220
- constructor(privateKey, tokenLifetimeSeconds = 300) {
1306
+ constructor(key, tokenLifetimeSeconds = 300) {
1221
1307
  super();
1222
- this._privateKey = privateKey;
1223
- this._publicKey = getPublicKey2(privateKey);
1308
+ if (isSigner(key)) {
1309
+ this._signer = key;
1310
+ } else {
1311
+ this._privateKey = key;
1312
+ this._signer = rawKeySigner(key);
1313
+ }
1314
+ this._publicKey = this._signer.publicKey;
1224
1315
  this._did = didFromPublicKey(this._publicKey);
1225
1316
  this._lifetime = tokenLifetimeSeconds;
1226
1317
  }
1227
1318
  apply(headers, audience) {
1228
- headers["Authorization"] = `Bearer ${this.identityToken(audience)}`;
1319
+ if (this._privateKey) {
1320
+ headers["Authorization"] = `Bearer ${this.identityToken(audience)}`;
1321
+ return;
1322
+ }
1323
+ return this.mintIdentityToken(audience).then((token) => {
1324
+ headers["Authorization"] = `Bearer ${token}`;
1325
+ });
1229
1326
  }
1230
1327
  /**
1231
1328
  * Mint a bearer-usable identity JWT for this key — the same token
@@ -1238,17 +1335,37 @@ var Ed25519Auth = class _Ed25519Auth extends Auth {
1238
1335
  * at any venue that accepts the caller's DID, so minting one is refused
1239
1336
  * rather than silently weakened.
1240
1337
  *
1338
+ * Raw-key instances only: a signer-backed instance signs asynchronously,
1339
+ * so use {@link mintIdentityToken}, which works for both.
1340
+ *
1241
1341
  * @param audience - The venue DID the token is bound to (`aud` claim).
1242
1342
  * @param lifetimeSeconds - Token lifetime; defaults to this instance's.
1243
1343
  */
1244
1344
  identityToken(audience, lifetimeSeconds) {
1345
+ const aud = this.resolveAudience(audience);
1346
+ if (!this._privateKey) {
1347
+ throw new CoviaError(
1348
+ "Ed25519Auth.identityToken() needs a raw private key; this instance signs through an Ed25519Signer, so use the async mintIdentityToken() instead."
1349
+ );
1350
+ }
1351
+ return createEdDSAJWT(this._privateKey, lifetimeSeconds ?? this._lifetime, aud);
1352
+ }
1353
+ /**
1354
+ * Async {@link identityToken} that works for raw-key and signer-backed
1355
+ * instances alike. Same token, same audience rules.
1356
+ */
1357
+ async mintIdentityToken(audience, lifetimeSeconds) {
1358
+ const aud = this.resolveAudience(audience);
1359
+ return createEdDSAJWTWith(this._signer, lifetimeSeconds ?? this._lifetime, aud);
1360
+ }
1361
+ resolveAudience(audience) {
1245
1362
  const aud = this._audience ?? (audience || void 0);
1246
1363
  if (!aud) {
1247
1364
  throw new CoviaError(
1248
1365
  "Ed25519Auth requires a venue audience to bind the token to: connect via Grid.connect()/Venue.connect() so the venue DID is known, or pin auth.audience explicitly."
1249
1366
  );
1250
1367
  }
1251
- return createEdDSAJWT(this._privateKey, lifetimeSeconds ?? this._lifetime, aud);
1368
+ return aud;
1252
1369
  }
1253
1370
  /** The caller's DID derived from the public key. */
1254
1371
  getDID() {
@@ -1277,7 +1394,17 @@ var Ed25519Auth = class _Ed25519Auth extends Auth {
1277
1394
  static fromHex(privateKeyHex, tokenLifetimeSeconds = 300) {
1278
1395
  return new _Ed25519Auth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
1279
1396
  }
1397
+ /**
1398
+ * Create from an {@link Ed25519Signer}, e.g. `await webCryptoSigner(keyPair)`
1399
+ * over a non-extractable WebCrypto key. Requests sign asynchronously.
1400
+ */
1401
+ static fromSigner(signer, tokenLifetimeSeconds = 300) {
1402
+ return new _Ed25519Auth(signer, tokenLifetimeSeconds);
1403
+ }
1280
1404
  };
1405
+ function isSigner(key) {
1406
+ return !ArrayBuffer.isView(key) && typeof key.sign === "function";
1407
+ }
1281
1408
  var KeyPairAuth = Ed25519Auth;
1282
1409
  var CredentialsHTTP = class {
1283
1410
  constructor(venueId, apiKey, userId) {
@@ -1701,7 +1828,7 @@ var AdapterManager = class {
1701
1828
  };
1702
1829
 
1703
1830
  // src/VenueTransport.ts
1704
- function requestOptions(venue, options) {
1831
+ async function requestOptions(venue, options) {
1705
1832
  const {
1706
1833
  contentType,
1707
1834
  headers: suppliedHeaders = {},
@@ -1712,19 +1839,19 @@ function requestOptions(venue, options) {
1712
1839
  if (effectiveContentType && headers["Content-Type"] === void 0) {
1713
1840
  headers["Content-Type"] = effectiveContentType;
1714
1841
  }
1715
- venue.auth.apply(headers, venue.venueId);
1842
+ await venue.auth.apply(headers, venue.venueId);
1716
1843
  return { ...request, headers };
1717
1844
  }
1718
- function venueJson(venue, path, options = {}) {
1845
+ async function venueJson(venue, path, options = {}) {
1719
1846
  return fetchWithError(
1720
1847
  `${venue.baseUrl}${path}`,
1721
- requestOptions(venue, options)
1848
+ await requestOptions(venue, options)
1722
1849
  );
1723
1850
  }
1724
- function venueStream(venue, path, options = {}) {
1851
+ async function venueStream(venue, path, options = {}) {
1725
1852
  return fetchStreamWithError(
1726
1853
  `${venue.baseUrl}${path}`,
1727
- requestOptions(venue, options)
1854
+ await requestOptions(venue, options)
1728
1855
  );
1729
1856
  }
1730
1857
 
@@ -4065,7 +4192,17 @@ function didFor(privateKey) {
4065
4192
  return `did:key:${encodePublicKey(getPublicKey2(privateKey))}`;
4066
4193
  }
4067
4194
  function createUCANJWT(privateKey, audienceDID, att, lifetimeSeconds, proofs = []) {
4068
- const multikey = encodePublicKey(getPublicKey2(privateKey));
4195
+ const signingInput = ucanSigningInput(getPublicKey2(privateKey), audienceDID, att, lifetimeSeconds, proofs);
4196
+ const signature = sign(encoder2.encode(signingInput), privateKey);
4197
+ return `${signingInput}.${base64UrlEncode(signature)}`;
4198
+ }
4199
+ async function createUCANJWTWith(signer, audienceDID, att, lifetimeSeconds, proofs = []) {
4200
+ const signingInput = ucanSigningInput(signer.publicKey, audienceDID, att, lifetimeSeconds, proofs);
4201
+ const signature = await signer.sign(encoder2.encode(signingInput));
4202
+ return `${signingInput}.${base64UrlEncode(signature)}`;
4203
+ }
4204
+ function ucanSigningInput(publicKey, audienceDID, att, lifetimeSeconds, proofs) {
4205
+ const multikey = encodePublicKey(publicKey);
4069
4206
  const nowSecs = Math.floor(Date.now() / 1e3);
4070
4207
  const header = JSON.stringify({ alg: "EdDSA", typ: "JWT", kid: multikey });
4071
4208
  const claims = {
@@ -4081,9 +4218,7 @@ function createUCANJWT(privateKey, audienceDID, att, lifetimeSeconds, proofs = [
4081
4218
  // CVMDouble the venue's UcanJwtValidator rejects outright (covia-sdk#46).
4082
4219
  exp: lifetimeSeconds === null ? null : Math.floor(nowSecs + lifetimeSeconds)
4083
4220
  };
4084
- const signingInput = `${base64UrlEncode(encoder2.encode(header))}.${base64UrlEncode(encoder2.encode(JSON.stringify(claims)))}`;
4085
- const signature = sign(encoder2.encode(signingInput), privateKey);
4086
- return `${signingInput}.${base64UrlEncode(signature)}`;
4221
+ return `${base64UrlEncode(encoder2.encode(header))}.${base64UrlEncode(encoder2.encode(JSON.stringify(claims)))}`;
4087
4222
  }
4088
4223
  function identityToken(privateKey, venueDID, lifetimeSeconds = 300) {
4089
4224
  return createUCANJWT(privateKey, venueDID, [], lifetimeSeconds);
@@ -4091,14 +4226,21 @@ function identityToken(privateKey, venueDID, lifetimeSeconds = 300) {
4091
4226
  function grant(ownerPrivateKey, audienceDID, withResource, can, lifetimeSeconds) {
4092
4227
  return createUCANJWT(ownerPrivateKey, audienceDID, [{ with: withResource, can }], lifetimeSeconds);
4093
4228
  }
4229
+ function grantWith(ownerSigner, audienceDID, withResource, can, lifetimeSeconds) {
4230
+ return createUCANJWTWith(ownerSigner, audienceDID, [{ with: withResource, can }], lifetimeSeconds);
4231
+ }
4094
4232
  function relayDelegation(privateKey, venueDID, lifetimeSeconds, caps = []) {
4095
4233
  const att = [{ with: didFor(privateKey), can: VENUE_RELAY }, ...caps];
4096
4234
  return createUCANJWT(privateKey, venueDID, att, lifetimeSeconds);
4097
4235
  }
4236
+ function relayDelegationWith(signer, venueDID, lifetimeSeconds, caps = []) {
4237
+ const att = [{ with: didFromPublicKey(signer.publicKey), can: VENUE_RELAY }, ...caps];
4238
+ return createUCANJWTWith(signer, venueDID, att, lifetimeSeconds);
4239
+ }
4098
4240
  /*! Bundled license information:
4099
4241
 
4100
4242
  @noble/ed25519/index.js:
4101
4243
  (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
4102
4244
  */
4103
4245
 
4104
- export { A2AManager, AdapterManager, Agent, AgentManager, AgentSessionNotFoundError, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BasicAuth, BearerAuth, ChatSession, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DLFSManager, DataAsset, Ed25519Auth, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, MCPError, MCPManager, MemoryManager, Namespace, NoAuth, NotFoundError, Operation, OperationManager, RateLimitError, RunStatus, ScopedWorkspace, SecretManager, SkillManager, UCANManager, UnsupportedVenueFeatureError, UserManager, VENUE_RELAY, Venue, VenueIdentityChangedError, WorkspaceManager, assetHash, createSSEEvent, createUCANJWT, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, hexToPrivateKey, identityToken, isDid, isJobComplete, isJobFinished, isJobPaused, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, relayDelegation, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates };
4246
+ export { A2AManager, AdapterManager, Agent, AgentManager, AgentSessionNotFoundError, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BasicAuth, BearerAuth, ChatSession, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DLFSManager, DataAsset, Ed25519Auth, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, MCPError, MCPManager, MemoryManager, Namespace, NoAuth, NotFoundError, Operation, OperationManager, RateLimitError, RunStatus, ScopedWorkspace, SecretManager, SkillManager, UCANManager, UnsupportedVenueFeatureError, UserManager, VENUE_RELAY, Venue, VenueIdentityChangedError, WorkspaceManager, assetHash, createSSEEvent, createUCANJWT, createUCANJWTWith, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, generateNonExtractableKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, grantWith, hexToPrivateKey, identityToken, importNonExtractableKey, isDid, isJobComplete, isJobFinished, isJobPaused, isWebCryptoEd25519Supported, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, rawKeySigner, relayDelegation, relayDelegationWith, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates, webCryptoSigner };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@covia/covia-sdk",
3
- "version": "1.19.1",
3
+ "version": "1.20.0",
4
4
  "description": "Typescript library for covia-ai",
5
5
  "packageManager": "pnpm@11.9.0",
6
6
  "main": "./dist/index.js",