mppx 0.21.2 → 0.21.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # mppx
2
2
 
3
+ ## 0.21.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 8e4cd5f: Preserved configured plugin payment policies when using persistent Tempo session accounts.
8
+ - ad2a467: Fixed `Challenge.deserialize` and `Challenge.serialize` to follow the MPP core grammar: payment method identifiers must be `1*LOWERALPHA` (a-z only), and a backslash in a quoted-string is a quoted-pair, so `\u2014` parses to the text `u2014` instead of being decoded. `Challenge.serialize` now throws for characters above U+00FF in any parameter except `description`, which keeps its `\uXXXX` escape so a 402 never fails on an em dash or emoji.
9
+
10
+ `Mppx.create` now throws at startup for a method name outside a-z, or for a `realm` above U+00FF on a transport that sends the Challenge in a header, instead of failing on every 402. `Challenge.deserializeList` skips an offer whose method id is outside a-z rather than rejecting the whole header, and the client keys payment retries without building a header or reading the display-only `description`.
11
+
12
+ The client now refuses a challenge from a server that escaped a parameter bound into the Challenge ID (such as `realm`) as `\uXXXX`, as servers before quoted-pair parsing did for characters above U+00FF: it skips such an offer when another is payable, and otherwise throws `Errors.LegacyUnicodeEscapedChallengeError` before creating, signing or broadcasting anything, since the server would reject the credential.
13
+
3
14
  ## 0.21.2
4
15
 
5
16
  ### Patch Changes
@@ -223,6 +223,10 @@ export declare namespace fromMethod {
223
223
  * ```
224
224
  */
225
225
  export declare function serialize(challenge: Challenge): string;
226
+ /** @internal Throws unless `method` matches the spec's method identifier grammar (a-z only). */
227
+ export declare function assertMethod(method: string): void;
228
+ /** @internal Throws unless `realm` can be sent in a header (no characters above U+00FF). */
229
+ export declare function assertRealm(realm: string): void;
226
230
  /**
227
231
  * Deserializes a WWW-Authenticate header value to a challenge.
228
232
  *
@@ -241,6 +245,21 @@ export declare function serialize(challenge: Challenge): string;
241
245
  * @returns The deserialized challenge.
242
246
  */
243
247
  export declare function deserialize<const methods extends readonly Method.Method[] | undefined = undefined>(value: string, options?: from.Options<methods>): from.ReturnType<from.Parameters, methods>;
248
+ /**
249
+ * Returns whether a challenge parsed from a header escaped an HMAC-bound parameter as `\\uXXXX`,
250
+ * as servers did before quoted-pair parsing. Paying it would fail verification after the payment
251
+ * may already have moved funds.
252
+ *
253
+ * @internal
254
+ */
255
+ export declare function isLegacyUnicodeEscaped(challenge: unknown): boolean;
256
+ /**
257
+ * Throws {@link Errors.LegacyUnicodeEscapedChallengeError} for a challenge that
258
+ * {@link isLegacyUnicodeEscaped} reports, before a credential is created for it.
259
+ *
260
+ * @internal
261
+ */
262
+ export declare function assertNotLegacyUnicodeEscaped(challenge: unknown): void;
244
263
  /**
245
264
  * Returns whether a `WWW-Authenticate` value contains a Payment challenge.
246
265
  *
package/dist/Challenge.js CHANGED
@@ -1,9 +1,26 @@
1
1
  import { Base64, Bytes, Hash } from 'ox';
2
2
  import * as Constants from './Constants.js';
3
+ import * as Errors from './Errors.js';
3
4
  import { constantTimeEqual } from './internal/constantTimeEqual.js';
4
5
  import * as PaymentRequest from './PaymentRequest.js';
5
6
  import * as z from './zod.js';
6
7
  const maxRequestParameterLength = 16 * 1024;
8
+ /**
9
+ * Marks a challenge parsed from a header whose HMAC-bound parameter carried a legacy `\\uXXXX`
10
+ * escape. A symbol key, so it survives spreads but stays out of JSON and the wire form.
11
+ */
12
+ const legacyUnicodeEscape = Symbol('mppx.Challenge.legacyUnicodeEscape');
13
+ /** Auth-params the challenge keeps and binds into its ID (see `idBindingInput`). */
14
+ const boundParams = new Set([
15
+ 'digest',
16
+ 'expires',
17
+ 'header',
18
+ 'intent',
19
+ 'method',
20
+ 'opaque',
21
+ 'realm',
22
+ 'request',
23
+ ]);
7
24
  const unsupportedCredentialHeaderMessage = 'Unsupported credential header: challenges may only select Payment-Authorization.';
8
25
  /**
9
26
  * Thrown when a challenge selects a credential header other than `Payment-Authorization`.
@@ -193,15 +210,20 @@ export function fromMethod(method, parameters) {
193
210
  * ```
194
211
  */
195
212
  export function serialize(challenge) {
213
+ // Re-serializing drops the backslash that marks a legacy escape, so a signer reading the new
214
+ // header would not see it.
215
+ assertNotLegacyUnicodeEscaped(challenge);
216
+ const { method } = challenge;
217
+ assertMethod(method);
196
218
  const parts = [
197
219
  authParam('id', challenge.id),
198
220
  authParam('realm', challenge.realm),
199
- authParam('method', challenge.method),
221
+ authParam('method', method),
200
222
  authParam('intent', challenge.intent),
201
223
  authParam('request', PaymentRequest.serialize(challenge.request)),
202
224
  ];
203
225
  if (challenge.description !== undefined)
204
- parts.push(authParam('description', challenge.description));
226
+ parts.push(authParam('description', challenge.description, { escapeUnicode: true }));
205
227
  if (challenge.digest !== undefined)
206
228
  parts.push(authParam('digest', challenge.digest));
207
229
  if (challenge.expires !== undefined)
@@ -215,19 +237,41 @@ export function serialize(challenge) {
215
237
  parts.push(authParam('opaque', PaymentRequest.serialize(challenge.meta)));
216
238
  return `${Constants.Schemes.payment} ${parts.join(', ')}`;
217
239
  }
240
+ /** Payment method identifier grammar: `1*LOWERALPHA` (a-z only). */
241
+ const methodPattern = /^[a-z]+$/;
242
+ /** @internal Thrown for a method identifier outside the spec's grammar. */
243
+ class InvalidMethodError extends Error {
244
+ name = 'InvalidMethodError';
245
+ constructor(method) {
246
+ super(`Invalid method: "${method}". Must be lowercase letters a-z per spec.`);
247
+ }
248
+ }
249
+ /** @internal Throws unless `method` matches the spec's method identifier grammar (a-z only). */
250
+ export function assertMethod(method) {
251
+ if (!methodPattern.test(method))
252
+ throw new InvalidMethodError(method);
253
+ }
254
+ /** @internal Throws unless `realm` can be sent in a header (no characters above U+00FF). */
255
+ export function assertRealm(realm) {
256
+ if (/[\u0100-\uffff]/.test(realm))
257
+ throw new Error('Invalid realm: characters above U+00FF cannot be sent in a header.');
258
+ }
218
259
  /** @internal */
219
- function authParam(name, value) {
260
+ function authParam(name, value, options = {}) {
220
261
  if (/[\r\n]/.test(value))
221
262
  throw new Error('Invalid quoted-string value.');
222
- const escaped = value
223
- .replace(/\\/g, '\\\\')
224
- .replace(/"/g, '\\"')
225
- // Header values must be ByteStrings (code points ≤ 0xFF): escape anything
226
- // above Latin-1 (em dashes, smart quotes, emoji in descriptions) so the
227
- // serialized challenge is always a legal header value instead of crashing
228
- // Response construction.
229
- .replace(/[\u0100-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
230
- return `${name}="${escaped}"`;
263
+ const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
264
+ // Header values must be ByteStrings (code points ≤ 0xFF). Receivers read a
265
+ // backslash as quoted-pair (`\\u2014` is the text `u2014`), so other
266
+ // characters cannot round-trip in a quoted-string.
267
+ if (!/[\u0100-\uffff]/.test(escaped))
268
+ return `${name}="${escaped}"`;
269
+ // The display-only description is not bound into the Challenge ID: keep the
270
+ // `\\uXXXX` escape there so a 402 never fails on an em dash or emoji in a
271
+ // product title. Receivers show the escape text.
272
+ if (options.escapeUnicode)
273
+ return `${name}="${escaped.replace(/[\u0100-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)}"`;
274
+ throw new Error(`Invalid ${name}: characters above U+00FF cannot be sent in a header.`);
231
275
  }
232
276
  /**
233
277
  * Deserializes a WWW-Authenticate header value to a challenge.
@@ -250,14 +294,15 @@ export function deserialize(value, options) {
250
294
  const params = extractPaymentAuthParams(value);
251
295
  if (!params)
252
296
  throw new Error('Missing Payment scheme.');
253
- const result = parseAuthParams(params);
297
+ const legacyEscaped = new Set();
298
+ const result = parseAuthParams(params, legacyEscaped);
254
299
  const { request, opaque, header, ...rest } = result;
255
300
  if (!request)
256
301
  throw new Error('Missing request parameter.');
257
302
  if (request.length > maxRequestParameterLength)
258
303
  throw new Error('Request parameter too large.');
259
- if (rest.method && !/^[a-z][a-z0-9:_-]*$/.test(rest.method))
260
- throw new Error(`Invalid method: "${rest.method}". Must be lowercase per spec.`);
304
+ if (rest.method !== undefined)
305
+ assertMethod(rest.method);
261
306
  // Validate the raw value before `from` treats `Authorization` as the omitted default: a
262
307
  // received challenge may only select `Payment-Authorization`.
263
308
  if (header !== undefined && !isPaymentAuthorizationHeader(header))
@@ -269,9 +314,35 @@ export function deserialize(value, options) {
269
314
  }, options);
270
315
  // Keep the spelling the server sent: the client echoes it unchanged, and the server's challenge
271
316
  // ID may bind that exact spelling.
272
- if (header === undefined)
273
- return challenge;
274
- return { ...challenge, header };
317
+ const parsed = (header === undefined ? challenge : { ...challenge, header });
318
+ // Servers before quoted-pair parsing escaped characters above U+00FF as `\\uXXXX`. Quoted-pair
319
+ // reads those as different text than the server bound into the challenge ID, so the client must
320
+ // not pay such a challenge. `description` and unknown params are not bound.
321
+ if ([...legacyEscaped].some((key) => boundParams.has(key)))
322
+ parsed[legacyUnicodeEscape] = true;
323
+ return parsed;
324
+ }
325
+ /**
326
+ * Returns whether a challenge parsed from a header escaped an HMAC-bound parameter as `\\uXXXX`,
327
+ * as servers did before quoted-pair parsing. Paying it would fail verification after the payment
328
+ * may already have moved funds.
329
+ *
330
+ * @internal
331
+ */
332
+ export function isLegacyUnicodeEscaped(challenge) {
333
+ return Boolean(challenge &&
334
+ typeof challenge === 'object' &&
335
+ challenge[legacyUnicodeEscape]);
336
+ }
337
+ /**
338
+ * Throws {@link Errors.LegacyUnicodeEscapedChallengeError} for a challenge that
339
+ * {@link isLegacyUnicodeEscaped} reports, before a credential is created for it.
340
+ *
341
+ * @internal
342
+ */
343
+ export function assertNotLegacyUnicodeEscaped(challenge) {
344
+ if (isLegacyUnicodeEscaped(challenge))
345
+ throw new Errors.LegacyUnicodeEscapedChallengeError();
275
346
  }
276
347
  /** @internal Extracts the `Payment` scheme from a WWW-Authenticate value that may contain multiple schemes. */
277
348
  function extractPaymentAuthParams(header) {
@@ -285,7 +356,7 @@ function extractPaymentAuthParams(header) {
285
356
  return header.slice(paramsStart);
286
357
  }
287
358
  /** @internal Parses auth-params with support for escaped quoted-string values. */
288
- function parseAuthParams(input) {
359
+ function parseAuthParams(input, legacyEscaped) {
289
360
  const result = Object.create(null);
290
361
  let i = 0;
291
362
  while (i < input.length) {
@@ -307,8 +378,10 @@ function parseAuthParams(input) {
307
378
  i++;
308
379
  while (i < input.length && /\s/.test(input[i] ?? ''))
309
380
  i++;
310
- const [value, nextIndex] = readAuthParamValue(input, i);
381
+ const [value, nextIndex, legacy] = readAuthParamValue(input, i);
311
382
  i = nextIndex;
383
+ if (legacy)
384
+ legacyEscaped?.add(key);
312
385
  if (key in result)
313
386
  throw new Error(`Duplicate parameter: ${key}`);
314
387
  result[key] = value;
@@ -328,23 +401,19 @@ function readAuthParamValue(input, start) {
328
401
  function readQuotedAuthParamValue(input, start) {
329
402
  let i = start;
330
403
  let escaped = false;
404
+ let legacyEscape = false;
331
405
  let segmentStart = start;
332
406
  let parts;
333
407
  while (i < input.length) {
334
408
  const char = input[i];
335
409
  i++;
336
410
  if (escaped) {
411
+ // quoted-pair (RFC 9110): drop the backslash and keep the next character
412
+ // as is, so `\\u2014` is the text `u2014`, not an escape.
413
+ if (char === 'u' && /^[0-9a-fA-F]{4}/.test(input.slice(i, i + 4)))
414
+ legacyEscape = true;
337
415
  parts ??= [];
338
- // `\\uXXXX` unescapes characters above Latin-1. Unambiguous: serializers
339
- // always double raw backslashes, so a bare `\\u` only ever comes from
340
- // the unicode escape in `authParam`.
341
- const hex = char === 'u' ? input.slice(i, i + 4) : undefined;
342
- if (hex && /^[0-9A-Fa-f]{4}$/.test(hex)) {
343
- parts.push(String.fromCharCode(Number.parseInt(hex, 16)));
344
- i += 4;
345
- }
346
- else
347
- parts.push(char);
416
+ parts.push(char);
348
417
  segmentStart = i;
349
418
  escaped = false;
350
419
  continue;
@@ -360,7 +429,7 @@ function readQuotedAuthParamValue(input, start) {
360
429
  const value = parts
361
430
  ? [...parts, input.slice(segmentStart, i - 1)].join('')
362
431
  : input.slice(start, i - 1);
363
- return [value, i];
432
+ return [value, i, legacyEscape];
364
433
  }
365
434
  }
366
435
  throw new Error('Unterminated quoted-string.');
@@ -524,6 +593,10 @@ export function deserializeList(value, options) {
524
593
  // but must not stop the client from paying another challenge.
525
594
  if (error instanceof UnsupportedCredentialHeaderError)
526
595
  return [];
596
+ // An offer for a method id outside the grammar can't be paid, but must not stop the
597
+ // client from paying another offer in the same header.
598
+ if (error instanceof InvalidMethodError)
599
+ return [];
527
600
  throw error;
528
601
  }
529
602
  });
package/dist/Errors.d.ts CHANGED
@@ -303,6 +303,19 @@ export declare namespace PaymentSimulationError {
303
303
  sender?: `0x${string}` | undefined;
304
304
  };
305
305
  }
306
+ /**
307
+ * The server escaped an HMAC-bound challenge parameter (such as `realm`) as `\\uXXXX`, as mppx
308
+ * servers before quoted-pair parsing did for characters above U+00FF. The client reads that
309
+ * escape as different text than the server bound into the challenge ID, so the server would
310
+ * reject the credential, possibly after the payment moved funds. The client stops before it
311
+ * creates, signs or broadcasts anything.
312
+ *
313
+ * Upgrade the server, or keep bound parameters within Latin-1.
314
+ */
315
+ export declare class LegacyUnicodeEscapedChallengeError extends Error {
316
+ readonly name = "LegacyUnicodeEscapedChallengeError";
317
+ constructor();
318
+ }
306
319
  /**
307
320
  * A `tempo/session` client would open a channel whose vouchers a TIP-1166 configurable account
308
321
  * signs, but the server's challenge does not advertise `configurableVouchers`, so the server
package/dist/Errors.js CHANGED
@@ -261,6 +261,21 @@ export class PaymentSimulationError extends Error {
261
261
  Object.defineProperty(this, 'cause', { configurable: true, value: cause, writable: true });
262
262
  }
263
263
  }
264
+ /**
265
+ * The server escaped an HMAC-bound challenge parameter (such as `realm`) as `\\uXXXX`, as mppx
266
+ * servers before quoted-pair parsing did for characters above U+00FF. The client reads that
267
+ * escape as different text than the server bound into the challenge ID, so the server would
268
+ * reject the credential, possibly after the payment moved funds. The client stops before it
269
+ * creates, signs or broadcasts anything.
270
+ *
271
+ * Upgrade the server, or keep bound parameters within Latin-1.
272
+ */
273
+ export class LegacyUnicodeEscapedChallengeError extends Error {
274
+ name = 'LegacyUnicodeEscapedChallengeError';
275
+ constructor() {
276
+ super('Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.');
277
+ }
278
+ }
264
279
  /**
265
280
  * A `tempo/session` client would open a channel whose vouchers a TIP-1166 configurable account
266
281
  * signs, but the server's challenge does not advertise `configurableVouchers`, so the server
package/dist/Method.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type * as Challenge from './Challenge.js';
1
+ import * as Challenge from './Challenge.js';
2
2
  import * as Credential from './Credential.js';
3
3
  import type * as Html from './internal/html/config.js';
4
4
  import type { DeepReadonly, ExactPartial, LooseOmit, MaybePromise } from './internal/types.js';
package/dist/Method.js CHANGED
@@ -1,3 +1,4 @@
1
+ import * as Challenge from './Challenge.js';
1
2
  import * as Credential from './Credential.js';
2
3
  import * as Errors from './Errors.js';
3
4
  import * as CredentialExpiry from './internal/CredentialExpiry.js';
@@ -125,7 +126,11 @@ export function toClient(method, options) {
125
126
  ...method,
126
127
  canHandleChallenge,
127
128
  context,
128
- createCredential,
129
+ // Refuse a legacy `\uXXXX`-escaped challenge before the method signs or broadcasts anything.
130
+ async createCredential(parameters) {
131
+ Challenge.assertNotLegacyUnicodeEscaped(parameters.challenge);
132
+ return createCredential.call(this, parameters);
133
+ },
129
134
  };
130
135
  }
131
136
  /**