@routr/common 2.26.0 → 2.27.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.
@@ -0,0 +1,41 @@
1
+ import { SipURI } from "./types";
2
+ /**
3
+ * The caller identity Routr rewrites toward a Trunk travels in its own
4
+ * Record-Route as parameters, so the dialog's later requests can be mapped back
5
+ * without state. Shared by the processor, which writes and reads them, and the
6
+ * trace sanitizer, which must rewrite inside them.
7
+ */
8
+ /**
9
+ * The Record-Route parameter names: [r]ewritten [f]rom or [c]allee (To),
10
+ * [o]riginal/[n]ew. Not "rto": a parser that looks for a header by searching for
11
+ * its name (SIPp does) finds "To" inside "rto=" on the Record-Route line.
12
+ */
13
+ export declare const IDENTITY_PARAMETERS: {
14
+ readonly fromOriginal: "rfo";
15
+ readonly fromNew: "rfn";
16
+ readonly toOriginal: "rco";
17
+ readonly toNew: "rcn";
18
+ };
19
+ /** Every identity parameter name, in the order above. */
20
+ export declare const IDENTITY_PARAMETER_NAMES: string[];
21
+ /** The identity a SIP URI carries, as stored in a Record-Route parameter. */
22
+ export interface Identity {
23
+ user?: string;
24
+ host: string;
25
+ userParam?: string;
26
+ }
27
+ /**
28
+ * Encodes an identity as base64url, which keeps it a SIP token (RFC 3261
29
+ * section 25.1): no quoting in the header, and it survives every hop unchanged.
30
+ *
31
+ * @param {SipURI} uri - The URI whose user, host and user parameter to encode
32
+ * @return {string} The base64url value
33
+ */
34
+ export declare const encodeIdentity: (uri: SipURI) => string;
35
+ /**
36
+ * Decodes an identity parameter value.
37
+ *
38
+ * @param {string} value - The base64url value
39
+ * @return {Identity | undefined} The identity, or undefined when it is not one
40
+ */
41
+ export declare const decodeIdentity: (value?: string) => Identity | undefined;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeIdentity = exports.encodeIdentity = exports.IDENTITY_PARAMETER_NAMES = exports.IDENTITY_PARAMETERS = void 0;
4
+ /**
5
+ * The caller identity Routr rewrites toward a Trunk travels in its own
6
+ * Record-Route as parameters, so the dialog's later requests can be mapped back
7
+ * without state. Shared by the processor, which writes and reads them, and the
8
+ * trace sanitizer, which must rewrite inside them.
9
+ */
10
+ /**
11
+ * The Record-Route parameter names: [r]ewritten [f]rom or [c]allee (To),
12
+ * [o]riginal/[n]ew. Not "rto": a parser that looks for a header by searching for
13
+ * its name (SIPp does) finds "To" inside "rto=" on the Record-Route line.
14
+ */
15
+ exports.IDENTITY_PARAMETERS = {
16
+ fromOriginal: "rfo",
17
+ fromNew: "rfn",
18
+ toOriginal: "rco",
19
+ toNew: "rcn"
20
+ };
21
+ /** Every identity parameter name, in the order above. */
22
+ exports.IDENTITY_PARAMETER_NAMES = Object.values(exports.IDENTITY_PARAMETERS);
23
+ /**
24
+ * Encodes an identity as base64url, which keeps it a SIP token (RFC 3261
25
+ * section 25.1): no quoting in the header, and it survives every hop unchanged.
26
+ *
27
+ * @param {SipURI} uri - The URI whose user, host and user parameter to encode
28
+ * @return {string} The base64url value
29
+ */
30
+ const encodeIdentity = (uri) => {
31
+ var _a;
32
+ return Buffer.from(`${(_a = uri.user) !== null && _a !== void 0 ? _a : ""}@${uri.host}${uri.userParam ? `;user=${uri.userParam}` : ""}`).toString("base64url");
33
+ };
34
+ exports.encodeIdentity = encodeIdentity;
35
+ /**
36
+ * Decodes an identity parameter value.
37
+ *
38
+ * @param {string} value - The base64url value
39
+ * @return {Identity | undefined} The identity, or undefined when it is not one
40
+ */
41
+ const decodeIdentity = (value) => {
42
+ if (!value)
43
+ return undefined;
44
+ const decoded = Buffer.from(value, "base64url").toString("utf8");
45
+ const [address, userParam] = decoded.split(";user=");
46
+ const at = address.lastIndexOf("@");
47
+ if (at < 0)
48
+ return undefined;
49
+ const user = address.slice(0, at);
50
+ return {
51
+ user: user || undefined,
52
+ host: address.slice(at + 1),
53
+ userParam: userParam || undefined
54
+ };
55
+ };
56
+ exports.decodeIdentity = decodeIdentity;
package/dist/index.d.ts CHANGED
@@ -15,4 +15,5 @@ export * as CommonErrors from "./errors";
15
15
  export * as ConnectSchemas from "./connect/schemas";
16
16
  export * as Verifier from "./verifier";
17
17
  export * as Trace from "./trace";
18
+ export * as Identity from "./identity";
18
19
  export * as Config from "./config";
package/dist/index.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Config = exports.Trace = exports.Verifier = exports.ConnectSchemas = exports.CommonErrors = exports.CommonTypes = exports.CommonResponse = exports.CommonRequester = exports.CommonConnect = exports.Assertions = exports.Tracer = exports.IpUtils = exports.Helper = exports.Redis = exports.Auth = exports.statusMap = exports.GRPC_SERVING_STATUS = exports.LOCATION_OBJECT_PROTO = exports.PROCESSOR_OBJECT_PROTO = exports.Method = exports.Transport = exports.getObjectProto = exports.createService = void 0;
36
+ exports.Config = exports.Identity = exports.Trace = exports.Verifier = exports.ConnectSchemas = exports.CommonErrors = exports.CommonTypes = exports.CommonResponse = exports.CommonRequester = exports.CommonConnect = exports.Assertions = exports.Tracer = exports.IpUtils = exports.Helper = exports.Redis = exports.Auth = exports.statusMap = exports.GRPC_SERVING_STATUS = exports.LOCATION_OBJECT_PROTO = exports.PROCESSOR_OBJECT_PROTO = exports.Method = exports.Transport = exports.getObjectProto = exports.createService = void 0;
37
37
  /*
38
38
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
39
39
  * http://github.com/fonoster/routr
@@ -76,4 +76,5 @@ exports.CommonErrors = __importStar(require("./errors"));
76
76
  exports.ConnectSchemas = __importStar(require("./connect/schemas"));
77
77
  exports.Verifier = __importStar(require("./verifier"));
78
78
  exports.Trace = __importStar(require("./trace"));
79
+ exports.Identity = __importStar(require("./identity"));
79
80
  exports.Config = __importStar(require("./config"));
@@ -8,6 +8,7 @@ export interface CorpusEntry {
8
8
  replay: boolean;
9
9
  findings: string[];
10
10
  note?: string;
11
+ draft?: boolean;
11
12
  }
12
13
  export interface CorpusManifest {
13
14
  resources: string;
@@ -24,6 +24,7 @@ exports.compareLive = compareLive;
24
24
  const types_1 = require("../types");
25
25
  const diff_1 = require("./diff");
26
26
  const normalize_1 = require("./normalize");
27
+ const redact_1 = require("./redact");
27
28
  const status_1 = require("./status");
28
29
  const types_2 = require("./types");
29
30
  /*
@@ -68,7 +69,10 @@ function parseManifest(input) {
68
69
  findings.some((f) => typeof f !== "string")) {
69
70
  throw new Error(`${e.file}: findings must be a list of rule ids`);
70
71
  }
71
- return Object.assign({ file: e.file, profiles, replay: e.replay !== false, findings: Array.from(new Set(findings)).sort() }, (e.note ? { note: e.note } : {}));
72
+ if (e.draft !== undefined && typeof e.draft !== "boolean") {
73
+ throw new Error(`${e.file}: draft must be true or false`);
74
+ }
75
+ return Object.assign(Object.assign({ file: e.file, profiles, replay: e.replay !== false, findings: Array.from(new Set(findings)).sort() }, (e.note ? { note: e.note } : {})), (e.draft ? { draft: true } : {}));
72
76
  });
73
77
  return { resources: m.resources, files };
74
78
  }
@@ -87,6 +91,56 @@ const outcomeOf = (live) => {
87
91
  }
88
92
  : { outcome: types_2.TraceOutcome.FORWARDED };
89
93
  };
94
+ // The media relay rewrites SDP bodies, and the compat chain never runs one (no
95
+ // RTPEngine), so a body the relay rewrote is not comparable on replay
96
+ const MEDIA_COMPONENT = /rtprelay/i;
97
+ /**
98
+ * Blanks, on both sides, what a recording cannot be compared on: a header the
99
+ * recorder redacted (its value is gone), and a body the media relay rewrote.
100
+ * Everything else, headers, routing and authentication included, still is.
101
+ *
102
+ * @param {TraceRecord} record - The recorded record, for its hops
103
+ * @param {SIPMessage} recorded - The recorded outgoing message, normalized
104
+ * @param {SIPMessage} replayed - The live outgoing message, normalized
105
+ */
106
+ function ignoreWhatTheRecordingCannotShow(record, recorded, replayed) {
107
+ var _a, _b;
108
+ ;
109
+ ((_a = recorded.extensions) !== null && _a !== void 0 ? _a : []).forEach((ext) => {
110
+ var _a;
111
+ if (ext.value !== redact_1.REDACTED)
112
+ return;
113
+ ((_a = replayed.extensions) !== null && _a !== void 0 ? _a : [])
114
+ .filter((e) => e.name.toLowerCase() === ext.name.toLowerCase())
115
+ .forEach((e) => (e.value = redact_1.REDACTED));
116
+ });
117
+ // Only when the relay actually rewrote the body; a relay that passed the
118
+ // message through leaves it comparable
119
+ const throughMedia = ((_b = record.hops) !== null && _b !== void 0 ? _b : []).some((h) => {
120
+ var _a;
121
+ const headers = (_a = h.diff) === null || _a === void 0 ? void 0 : _a.headers;
122
+ return (MEDIA_COMPONENT.test(h.component) &&
123
+ !!headers &&
124
+ ("Body" in headers.changed ||
125
+ "Body" in headers.added ||
126
+ "Body" in headers.removed));
127
+ });
128
+ if (throughMedia) {
129
+ recorded.body = withoutMediaDetails(recorded.body);
130
+ replayed.body = withoutMediaDetails(replayed.body);
131
+ }
132
+ }
133
+ /**
134
+ * Replaces the media a body describes with a placeholder media line. The diff
135
+ * summarizes a body by its m= and c= lines, so a body that has media still
136
+ * compares as present and one that lost its SDP still shows as removed.
137
+ *
138
+ * @param {string} body - The body, possibly empty
139
+ * @return {string} The placeholder, or the body unchanged when it has no media
140
+ */
141
+ function withoutMediaDetails(body) {
142
+ return /^(m|c)=/m.test(body !== null && body !== void 0 ? body : "") ? "m=*" : body;
143
+ }
90
144
  /**
91
145
  * Compares what the live chain answered with what the recording holds,
92
146
  * after normalizing the values that differ between runs. Timing never
@@ -114,7 +168,10 @@ function compareLive(record, live) {
114
168
  ? { seq: record.seq, reason: "one side has no outgoing message" }
115
169
  : undefined;
116
170
  }
117
- const diff = (0, diff_1.diffMessages)((0, normalize_1.normalizeMessage)(record.response.message), (0, normalize_1.normalizeMessage)(live.message));
171
+ const recorded = (0, normalize_1.normalizeMessage)(record.response.message);
172
+ const replayed = (0, normalize_1.normalizeMessage)(live.message);
173
+ ignoreWhatTheRecordingCannotShow(record, recorded, replayed);
174
+ const diff = (0, diff_1.diffMessages)(recorded, replayed);
118
175
  if ((0, diff_1.isEmptyDiff)(diff))
119
176
  return undefined;
120
177
  const changed = [
@@ -40,14 +40,24 @@ exports.default = (0, types_1.defineRule)({
40
40
  ((_b = (0, facts_1.statusOf)(r)) !== null && _b !== void 0 ? _b : 0) < 300;
41
41
  })
42
42
  .filter((ok) => {
43
- var _a;
44
- const n = (_a = (0, facts_1.cseqOf)((0, facts_1.inbound)(ok))) === null || _a === void 0 ? void 0 : _a.number;
43
+ var _a, _b;
44
+ // The ACK carries the caller's CSeq, which is the CSeq of the INVITE
45
+ // forwarded before this 2xx. It differs from the 2xx's own when the
46
+ // EdgePort authenticated on the caller's behalf: the retry raised the
47
+ // CSeq on the provider leg alone.
48
+ const forwarded = [...call]
49
+ .reverse()
50
+ .find((r) => (0, facts_1.isRequest)(r) && r.method === "INVITE" && r.seq < ok.seq);
51
+ const numbers = new Set([
52
+ (_a = (0, facts_1.cseqOf)((0, facts_1.inbound)(ok))) === null || _a === void 0 ? void 0 : _a.number,
53
+ forwarded && ((_b = (0, facts_1.cseqOf)((0, facts_1.inbound)(forwarded))) === null || _b === void 0 ? void 0 : _b.number)
54
+ ].filter((n) => n !== undefined));
45
55
  return !call.some((r) => {
46
56
  var _a;
47
57
  return (0, facts_1.isRequest)(r) &&
48
58
  r.method === "ACK" &&
49
59
  r.seq > ok.seq &&
50
- ((_a = (0, facts_1.cseqOf)((0, facts_1.inbound)(r))) === null || _a === void 0 ? void 0 : _a.number) === n;
60
+ numbers.has((_a = (0, facts_1.cseqOf)((0, facts_1.inbound)(r))) === null || _a === void 0 ? void 0 : _a.number);
51
61
  });
52
62
  });
53
63
  if (unacked.length) {
@@ -13,18 +13,22 @@ export interface SanitizeOptions {
13
13
  */
14
14
  export declare class UnknownCredentialError extends Error {
15
15
  readonly username: string;
16
+ readonly recordedUsername?: string;
16
17
  /**
17
- * @param {string} username - The digest username without a credential
18
+ * @param {string} username - The digest username without a credential, as it
19
+ * reads after the rewrites (the one looked up)
18
20
  * @param {number} seq - The record it appears on
21
+ * @param {string} recordedUsername - The username as recorded, when a rewrite
22
+ * changed it
19
23
  */
20
- constructor(username: string, seq: number);
24
+ constructor(username: string, seq: number, recordedUsername?: string);
21
25
  }
22
26
  /**
23
- * Makes a recording committable as a known-good: every digest response is
24
- * recomputed with the test password for its username (the digest is
25
- * stateless, so the record keeps authenticating), then each rewrite is
26
- * applied to every string so numbers, hosts and addresses stay consistent
27
- * across the file.
27
+ * Makes a recording committable as a known-good. First each rewrite is applied
28
+ * to every string, so numbers, hosts and addresses stay consistent across the
29
+ * file. Then every digest response is recomputed with the test password for its
30
+ * username, as that username reads after the rewrites (the digest is stateless,
31
+ * so the record keeps authenticating on replay).
28
32
  *
29
33
  * @param {TraceRecord} record - A record, redacted or not
30
34
  * @param {SanitizeOptions} options - Credentials and rewrites
@@ -21,6 +21,7 @@ exports.credentialsFromResources = credentialsFromResources;
21
21
  * See the License for the specific language governing permissions and
22
22
  * limitations under the License.
23
23
  */
24
+ const identity_1 = require("../identity");
24
25
  const auth_1 = require("../auth");
25
26
  /**
26
27
  * Thrown when a record carries an Authorization whose username has no
@@ -28,47 +29,118 @@ const auth_1 = require("../auth");
28
29
  */
29
30
  class UnknownCredentialError extends Error {
30
31
  /**
31
- * @param {string} username - The digest username without a credential
32
+ * @param {string} username - The digest username without a credential, as it
33
+ * reads after the rewrites (the one looked up)
32
34
  * @param {number} seq - The record it appears on
35
+ * @param {string} recordedUsername - The username as recorded, when a rewrite
36
+ * changed it
33
37
  */
34
- constructor(username, seq) {
35
- super(`record ${seq}: no credential for digest username "${username}"`);
38
+ constructor(username, seq, recordedUsername) {
39
+ const recorded = recordedUsername && recordedUsername !== username
40
+ ? ` (recorded as "${recordedUsername}")`
41
+ : "";
42
+ super(`record ${seq}: no credential for digest username "${username}"${recorded}`);
36
43
  this.name = "UnknownCredentialError";
37
44
  this.username = username;
45
+ if (recorded)
46
+ this.recordedUsername = recordedUsername;
38
47
  }
39
48
  }
40
49
  exports.UnknownCredentialError = UnknownCredentialError;
41
50
  /**
42
- * Makes a recording committable as a known-good: every digest response is
43
- * recomputed with the test password for its username (the digest is
44
- * stateless, so the record keeps authenticating), then each rewrite is
45
- * applied to every string so numbers, hosts and addresses stay consistent
46
- * across the file.
51
+ * Makes a recording committable as a known-good. First each rewrite is applied
52
+ * to every string, so numbers, hosts and addresses stay consistent across the
53
+ * file. Then every digest response is recomputed with the test password for its
54
+ * username, as that username reads after the rewrites (the digest is stateless,
55
+ * so the record keeps authenticating on replay).
47
56
  *
48
57
  * @param {TraceRecord} record - A record, redacted or not
49
58
  * @param {SanitizeOptions} options - Credentials and rewrites
50
59
  * @return {TraceRecord} A sanitized copy
51
60
  */
52
61
  function sanitizeRecord(record, options) {
53
- var _a, _b;
54
- const copy = JSON.parse(JSON.stringify(record));
55
- const messages = [copy.request.message, (_a = copy.response) === null || _a === void 0 ? void 0 : _a.message].filter(Boolean);
56
- messages.forEach((m) => {
57
- var _a;
58
- const auth = m.authorization;
62
+ var _a, _b, _c;
63
+ // Rewrite first: a digest covers the URI it was computed for, and a rewrite
64
+ // can change that URI (the number in sip:+<E.164>@...). Recomputing after
65
+ // the rewrite keeps the record authenticating on replay.
66
+ const copy = applyRewrites(JSON.parse(JSON.stringify(record)), (_a = options.rewrites) !== null && _a !== void 0 ? _a : []);
67
+ const recorded = [record.request.message, (_b = record.response) === null || _b === void 0 ? void 0 : _b.message];
68
+ const messages = [copy.request.message, (_c = copy.response) === null || _c === void 0 ? void 0 : _c.message];
69
+ messages.forEach((m, i) => {
70
+ var _a, _b;
71
+ const auth = m === null || m === void 0 ? void 0 : m.authorization;
59
72
  if (!(auth === null || auth === void 0 ? void 0 : auth.username))
60
73
  return;
61
74
  const cred = options.credentials.find((c) => c.username === auth.username);
62
- if (!cred)
63
- throw new UnknownCredentialError(auth.username, record.seq);
64
- const method = ((_a = auth.method) !== null && _a !== void 0 ? _a : copy.method);
75
+ if (!cred) {
76
+ throw new UnknownCredentialError(auth.username, record.seq, (_b = (_a = recorded[i]) === null || _a === void 0 ? void 0 : _a.authorization) === null || _b === void 0 ? void 0 : _b.username);
77
+ }
78
+ // The recorder writes an empty method on the digest; the record's own
79
+ // method is the one the digest covers (RFC 2617 A2 = method:uri)
80
+ const method = (auth.method || copy.method);
65
81
  auth.response = (0, auth_1.calculateAuthResponse)(Object.assign(Object.assign({}, auth), { method }), { username: cred.username, secret: cred.password });
66
82
  });
67
- const rewrites = (_b = options.rewrites) !== null && _b !== void 0 ? _b : [];
83
+ return copy;
84
+ }
85
+ /**
86
+ * Applies the literal rewrites to every string of a record, including inside
87
+ * Routr's base64url identity parameters.
88
+ *
89
+ * @param {TraceRecord} record - The record to rewrite
90
+ * @param {Array<[string, string]>} rewrites - from/to pairs, applied in order
91
+ * @return {TraceRecord} The rewritten record
92
+ */
93
+ function applyRewrites(record, rewrites) {
68
94
  if (!rewrites.length)
69
- return copy;
70
- const text = rewrites.reduce((acc, [from, to]) => acc.split(from).join(to), JSON.stringify(copy));
71
- return JSON.parse(text);
95
+ return record;
96
+ const rewrite = (value) => rewrites.reduce((acc, [from, to]) => acc.split(from).join(to), value);
97
+ const text = JSON.stringify(rewriteEncodedIdentities(record, rewrite));
98
+ // The same parameters also travel inside header lines kept as text
99
+ // (";rfo=...;rfn=..." in a hop's diff); base64url has no quote, so they are
100
+ // safe to match in the JSON text
101
+ const encodedInText = new RegExp(`\\b(${ENCODED_IDENTITY_PARAMETERS.join("|")})=([A-Za-z0-9_-]+)`, "g");
102
+ return JSON.parse(rewrite(text.replace(encodedInText, (_m, name, value) => `${name}=${reencode(value, rewrite)}`)));
103
+ }
104
+ /**
105
+ * Decodes a base64url identity parameter, rewrites it and encodes it again.
106
+ *
107
+ * @param {string} value - The base64url value
108
+ * @param {Function} rewrite - The literal rewrites
109
+ * @return {string} The rewritten value, base64url
110
+ */
111
+ function reencode(value, rewrite) {
112
+ const decoded = Buffer.from(value, "base64url").toString("utf8");
113
+ const rewritten = rewrite(decoded);
114
+ // Untouched unless a rewrite applied: decoding a value that is not UTF-8 text
115
+ // (a parameter with the same name that is not Routr's) would otherwise alter it
116
+ return rewritten === decoded
117
+ ? value
118
+ : Buffer.from(rewritten, "utf8").toString("base64url");
119
+ }
120
+ // Record-Route parameters in which Routr keeps the caller identity it rewrote
121
+ // toward a Trunk, as base64url (see the processor's identity alterations). A
122
+ // literal rewrite cannot see inside them, so the real number and host would
123
+ // survive sanitizing; they are decoded, rewritten and encoded again.
124
+ const ENCODED_IDENTITY_PARAMETERS = identity_1.IDENTITY_PARAMETER_NAMES;
125
+ /**
126
+ * Rewrites the identity parameters wherever they are a field of the record.
127
+ *
128
+ * @param {T} value - Any part of the record
129
+ * @param {Function} rewrite - The literal rewrites
130
+ * @return {T} A copy with those parameters rewritten
131
+ */
132
+ function rewriteEncodedIdentities(value, rewrite) {
133
+ if (Array.isArray(value)) {
134
+ return value.map((v) => rewriteEncodedIdentities(v, rewrite));
135
+ }
136
+ if (!value || typeof value !== "object")
137
+ return value;
138
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => {
139
+ if (ENCODED_IDENTITY_PARAMETERS.includes(k) && typeof v === "string") {
140
+ return [k, reencode(v, rewrite)];
141
+ }
142
+ return [k, rewriteEncodedIdentities(v, rewrite)];
143
+ }));
72
144
  }
73
145
  /**
74
146
  * Reads credentials out of a simpledata credentials.yaml already parsed.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/common",
3
- "version": "2.26.0",
3
+ "version": "2.27.0",
4
4
  "description": "Common package",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/routr#readme",
@@ -61,5 +61,5 @@
61
61
  "devDependencies": {
62
62
  "@types/js-yaml": "^4.0.5"
63
63
  },
64
- "gitHead": "c8278f328a3c763ff677001fbeb49690c0bc8cf3"
64
+ "gitHead": "826c897ddd664991f4c6376bae37838c0b5cd362"
65
65
  }