mppx 0.19.1 → 0.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.
Files changed (28) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/cli/cli.js +2 -2
  3. package/dist/extensions/identity/erc8004/Constants.d.ts +20 -0
  4. package/dist/extensions/identity/erc8004/Constants.js +20 -0
  5. package/dist/extensions/identity/erc8004/Types.d.ts +11 -0
  6. package/dist/extensions/identity/erc8004/Types.js +2 -0
  7. package/dist/extensions/identity/erc8004/client/index.d.ts +33 -0
  8. package/dist/extensions/identity/erc8004/client/index.js +33 -0
  9. package/dist/extensions/identity/erc8004/index.d.ts +5 -0
  10. package/dist/extensions/identity/erc8004/index.js +4 -0
  11. package/dist/extensions/identity/erc8004/internal/Agent.d.ts +21 -0
  12. package/dist/extensions/identity/erc8004/internal/Agent.js +24 -0
  13. package/dist/extensions/identity/erc8004/server/index.d.ts +44 -0
  14. package/dist/extensions/identity/erc8004/server/index.js +178 -0
  15. package/dist/extensions/identity/index.d.ts +2 -0
  16. package/dist/extensions/identity/index.js +2 -0
  17. package/dist/identity/Headers.d.ts +1 -1
  18. package/dist/identity/Headers.js +2 -0
  19. package/dist/internal/version.d.ts +2 -2
  20. package/dist/internal/version.js +1 -1
  21. package/dist/proxy/Proxy.js +47 -9
  22. package/dist/tempo/server/internal/html.gen.js +1 -1
  23. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  24. package/dist/tempo/session/server/CredentialVerification.js +44 -0
  25. package/dist/tempo/session/server/MeteredStream.d.ts +2 -0
  26. package/dist/tempo/session/server/MeteredStream.js +11 -0
  27. package/dist/tempo/session/server/Sse.js +9 -4
  28. package/package.json +5 -1
@@ -34,6 +34,8 @@ export declare function assertCredentialSourceCanSpend(parameters: {
34
34
  channel: Pick<ChannelStore.State, 'authorizedSigner' | 'payer'>;
35
35
  source?: string | undefined;
36
36
  }): void;
37
+ /** Binds an opening payment to the payer authenticated by its signed transaction. */
38
+ export declare function assertCredentialSourceIsPayer(source: string | undefined, chainId: number, payer: Address, serializedTransaction: Hex, client: Chain.TransactionClient): Promise<void>;
37
39
  /** Shared action and channel fields required on every session credential payload. */
38
40
  export type SessionCredentialPayloadHeader = {
39
41
  /** Credential action discriminator. */
@@ -1,4 +1,6 @@
1
+ import { TxEnvelopeTempo } from 'ox/tempo';
1
2
  import { isAddress, isAddressEqual, zeroAddress, } from 'viem';
3
+ import { Actions } from 'viem/tempo';
2
4
  import { AmountExceedsDepositError, ChannelClosedError, ChannelNotFoundError, DeltaTooSmallError, InsufficientBalanceError, InvalidSignatureError, VerificationFailedError, } from '../../../Errors.js';
3
5
  import * as Chain from '../precompile/Chain.js';
4
6
  import { readChannelClosedReceiptFields } from '../precompile/Chain.js';
@@ -8,6 +10,7 @@ import * as Voucher from '../precompile/Voucher.js';
8
10
  import * as ChannelStore from './ChannelStore.js';
9
11
  import { getChallengePaymentFields } from './RequestState.js';
10
12
  import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, trackSendAttempts, } from './Settlement.js';
13
+ import { verifiedPayer } from './SponsorshipLimit.js';
11
14
  /** Returns the effective voucher signer for a TIP-1034 descriptor. */
12
15
  export function authorizedSigner(descriptor) {
13
16
  return isAddressEqual(descriptor.authorizedSigner, zeroAddress)
@@ -96,6 +99,45 @@ export function assertCredentialSourceCanSpend(parameters) {
96
99
  reason: 'credential source does not match channel payer or authorized signer',
97
100
  });
98
101
  }
102
+ /** Binds an opening payment to the payer authenticated by its signed transaction. */
103
+ export async function assertCredentialSourceIsPayer(source, chainId, payer, serializedTransaction, client) {
104
+ if (source === undefined)
105
+ return;
106
+ if (!isAddressEqual(readCredentialSourceAddress(source, chainId), payer))
107
+ throw new VerificationFailedError({
108
+ reason: 'credential source does not match transaction payer',
109
+ });
110
+ let valid = false;
111
+ try {
112
+ const signer = verifiedPayer(serializedTransaction);
113
+ const { signature, keyAuthorization } = TxEnvelopeTempo.deserialize(serializedTransaction);
114
+ if (signer && signature?.type !== 'keychain')
115
+ valid = isAddressEqual(signer, payer);
116
+ else if (signer &&
117
+ signature?.type === 'keychain' &&
118
+ isAddressEqual(signature.userAddress, payer)) {
119
+ if (keyAuthorization)
120
+ valid =
121
+ isAddressEqual(signer, payer) &&
122
+ (keyAuthorization.chainId === 0n || keyAuthorization.chainId === BigInt(chainId)) &&
123
+ (keyAuthorization.expiry == null || keyAuthorization.expiry > Date.now() / 1_000);
124
+ else {
125
+ const metadata = await Actions.accessKey.getMetadata(client, {
126
+ account: payer,
127
+ accessKey: signer,
128
+ });
129
+ valid = !metadata.isRevoked && metadata.expiry > BigInt(Math.floor(Date.now() / 1_000));
130
+ }
131
+ }
132
+ }
133
+ catch {
134
+ // Unavailable authorization state cannot authenticate a claimed identity.
135
+ }
136
+ if (!valid)
137
+ throw new VerificationFailedError({
138
+ reason: 'credential source is not authenticated by transaction signature',
139
+ });
140
+ }
99
141
  function readCredentialSourceAddress(source, chainId) {
100
142
  const prefix = `did:pkh:eip155:${chainId}:`;
101
143
  if (!source?.startsWith(prefix))
@@ -302,6 +344,7 @@ async function validateOpenCredential(parameters, payload) {
302
344
  requestAmount: request.amount,
303
345
  });
304
346
  assertSameDescriptor(transaction.descriptor, payload.descriptor);
347
+ await assertCredentialSourceIsPayer(parameters.credentialSource, chainId, transaction.descriptor.payer, payload.transaction, client);
305
348
  if (cumulativeAmount > transaction.openDeposit)
306
349
  throw new AmountExceedsDepositError({ reason: 'voucher amount exceeds open deposit' });
307
350
  const valid = await Voucher.verifyVoucher(escrow, chainId, { channelId, cumulativeAmount, signature: payload.signature }, authorizedSigner(transaction.descriptor));
@@ -538,6 +581,7 @@ async function handleOpenCredential(parameters) {
538
581
  requestAmount: request.amount,
539
582
  });
540
583
  assertSameDescriptor(prepared.descriptor, payload.descriptor);
584
+ await assertCredentialSourceIsPayer(parameters.credentialSource, chainId, prepared.descriptor.payer, payload.transaction, client);
541
585
  if (cumulativeAmount > prepared.openDeposit)
542
586
  throw new AmountExceedsDepositError({ reason: 'voucher amount exceeds open deposit' });
543
587
  const valid = await Voucher.verifyVoucher(escrow, chainId, { channelId, cumulativeAmount: cumulativeAmount, signature: payload.signature }, authorizedSigner(prepared.descriptor));
@@ -52,4 +52,6 @@ export type MeteredStreamOptions = {
52
52
  };
53
53
  /** Applies voucher reservation and spend commits to an async session stream. */
54
54
  export declare function meterIterable(options: MeteredStreamOptions): AsyncGenerator<string>;
55
+ /** Whether an automatic source would start billable per-item work before a manual charge. */
56
+ export declare function requiresManualCharge(options: Pick<MeteredStreamOptions, 'generate' | 'tickCost' | 'chargeOnce'>): boolean;
55
57
  //# sourceMappingURL=MeteredStream.d.ts.map
@@ -2,6 +2,8 @@ import { commitReservedCharges, releaseReservedCharges, reserveChargeOrWait } fr
2
2
  /** Applies voucher reservation and spend commits to an async session stream. */
3
3
  export async function* meterIterable(options) {
4
4
  const manual = typeof options.generate === 'function';
5
+ if (requiresManualCharge(options))
6
+ throw new TypeError('Billable per-item streams require a generator that calls stream.charge() before starting work.');
5
7
  let prepaidUnits = options.prepaidUnits ?? 0;
6
8
  const signal = options.signal ?? new AbortController().signal;
7
9
  const reservation = {
@@ -56,6 +58,11 @@ export async function* meterIterable(options) {
56
58
  await options.onChargeCommitted?.(channel);
57
59
  };
58
60
  try {
61
+ if (!manual && options.chargeOnce) {
62
+ await charge();
63
+ await commit();
64
+ charged = true;
65
+ }
59
66
  const iterable = typeof options.generate === 'function'
60
67
  ? options.generate({ charge, signal })
61
68
  : options.generate;
@@ -88,4 +95,8 @@ export async function* meterIterable(options) {
88
95
  await releaseReservedCharges(reservation);
89
96
  }
90
97
  }
98
+ /** Whether an automatic source would start billable per-item work before a manual charge. */
99
+ export function requiresManualCharge(options) {
100
+ return typeof options.generate !== 'function' && options.tickCost > 0n && !options.chargeOnce;
101
+ }
91
102
  //# sourceMappingURL=MeteredStream.js.map
@@ -2,7 +2,7 @@ import * as Constants from '../../../Constants.js';
2
2
  import * as Credential from '../../../Credential.js';
3
3
  import { createSessionReceipt, extractData, formatMessageEvent, formatNeedVoucherEvent, formatReceiptEvent, readSessionChallengeAmount, requireSessionCredentialContext, } from '../precompile/Protocol.js';
4
4
  import * as ChannelStore from './ChannelStore.js';
5
- import { meterIterable, } from './MeteredStream.js';
5
+ import { meterIterable, requiresManualCharge, } from './MeteredStream.js';
6
6
  /** Exposes durable retry information when no refund hook is configured or it fails. */
7
7
  export class PrepaidRefundError extends Error {
8
8
  refund;
@@ -110,10 +110,15 @@ export function serve(options) {
110
110
  throw new Error('prepaidUnits must be a non-negative safe integer');
111
111
  const refundIdempotencyKey = options.refundIdempotencyKey ?? `stream:${globalThis.crypto.randomUUID()}`;
112
112
  ChannelStore.assertIdempotencyOptions({ idempotencyKey: refundIdempotencyKey });
113
- const refundOptions = { ...options, refundIdempotencyKey };
113
+ const rejectedAutomatic = requiresManualCharge(options);
114
+ const refundOptions = {
115
+ ...options,
116
+ autoCreditPrepaid: options.autoCreditPrepaid || rejectedAutomatic,
117
+ refundIdempotencyKey,
118
+ };
114
119
  const clearObligation = () => clearPrepaidRefund(store, channelId, refundIdempotencyKey);
115
120
  const creditFailedDelivery = async () => {
116
- if (!options.autoCreditPrepaid)
121
+ if (!refundOptions.autoCreditPrepaid)
117
122
  return clearObligation();
118
123
  if (undeliveredPrepaidUnits === 0 || tickCost === 0n) {
119
124
  await clearObligation();
@@ -206,7 +211,7 @@ export function serve(options) {
206
211
  .catch(() => { });
207
212
  termination = preparation
208
213
  .catch(() => { })
209
- .then(clearObligation)
214
+ .then(rejectedAutomatic ? creditFailedDelivery : clearObligation)
210
215
  .finally(() => {
211
216
  try {
212
217
  streamController?.close();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mppx",
3
3
  "type": "module",
4
- "version": "0.19.1",
4
+ "version": "0.20.0",
5
5
  "main": "./dist/index.js",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/wevm/mppx#readme",
@@ -143,6 +143,10 @@
143
143
  "types": "./dist/extensions/identity/tap/index.d.ts",
144
144
  "default": "./dist/extensions/identity/tap/index.js"
145
145
  },
146
+ "./extensions/identity/erc8004": {
147
+ "types": "./dist/extensions/identity/erc8004/index.d.ts",
148
+ "default": "./dist/extensions/identity/erc8004/index.js"
149
+ },
146
150
  "./extensions/identity/email-otp": {
147
151
  "types": "./dist/extensions/identity/email-otp/index.d.ts",
148
152
  "default": "./dist/extensions/identity/email-otp/index.js"