@routr/common 2.25.4 → 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,2 @@
1
+ export { interpolateEnv } from "./interpolate_env";
2
+ export { resolveSecretRefs } from "./resolve_secret_refs";
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveSecretRefs = exports.interpolateEnv = void 0;
4
+ /*
5
+ * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
6
+ * http://github.com/fonoster/routr
7
+ *
8
+ * This file is part of Routr.
9
+ *
10
+ * Licensed under the MIT License (the "License");
11
+ * you may not use this file except in compliance with
12
+ * the License. You may obtain a copy of the License at
13
+ *
14
+ * https://opensource.org/licenses/MIT
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ var interpolate_env_1 = require("./interpolate_env");
23
+ Object.defineProperty(exports, "interpolateEnv", { enumerable: true, get: function () { return interpolate_env_1.interpolateEnv; } });
24
+ var resolve_secret_refs_1 = require("./resolve_secret_refs");
25
+ Object.defineProperty(exports, "resolveSecretRefs", { enumerable: true, get: function () { return resolve_secret_refs_1.resolveSecretRefs; } });
@@ -0,0 +1,19 @@
1
+ import { z } from "zod/v4";
2
+ export declare const interpolateEnvSchema: z.ZodObject<{
3
+ input: z.ZodUnknown;
4
+ env: z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>;
5
+ allowedPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
6
+ }, z.core.$strip>;
7
+ export type InterpolateEnvParams<T> = Omit<z.infer<typeof interpolateEnvSchema>, "input"> & {
8
+ input: T;
9
+ };
10
+ /**
11
+ * Returns a copy of a parsed config with `${VAR}` and `${VAR:-default}`
12
+ * references in its strings resolved from `env`. The input is not mutated.
13
+ * Errors name the key path where they happened.
14
+ *
15
+ * @param {InterpolateEnvParams} params - The config, env and allowed paths
16
+ * @return {T} A copy of the config with references resolved
17
+ * @throws {ValidationError} When the params are invalid
18
+ */
19
+ export declare function interpolateEnv<T>(params: InterpolateEnvParams<T>): T;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.interpolateEnvSchema = void 0;
4
+ exports.interpolateEnv = interpolateEnv;
5
+ /*
6
+ * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster/routr
8
+ *
9
+ * This file is part of Routr.
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const v4_1 = require("zod/v4");
24
+ const validation_error_1 = require("../validation_error");
25
+ exports.interpolateEnvSchema = v4_1.z.object({
26
+ input: v4_1.z.unknown(),
27
+ env: v4_1.z.record(v4_1.z.string(), v4_1.z.string({ error: "env values must be strings" }).optional(), { error: "env must be an object of environment variables" }),
28
+ allowedPaths: v4_1.z
29
+ .array(v4_1.z.string(), { error: "allowedPaths must be an array of key paths" })
30
+ .optional()
31
+ });
32
+ /**
33
+ * Shell / docker-compose style variable interpolation for config files.
34
+ *
35
+ * Supported forms inside any string value:
36
+ * - `${VAR}` -> value of VAR; throws if VAR is unset or empty
37
+ * - `${VAR:-default}` -> value of VAR, or `default` when VAR is unset or empty
38
+ *
39
+ * Anything that is not a `${...}` reference is left untouched, so plain
40
+ * literals (`http://asterisk:8088`, `$5.00`, ...) pass through unchanged.
41
+ */
42
+ const VAR_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/g;
43
+ const HAS_REFERENCE = /\$\{[^}]*\}/;
44
+ /**
45
+ * Replaces every `${...}` reference in one string.
46
+ *
47
+ * @param {string} value - The string to interpolate
48
+ * @param {Env} env - The environment to read variables from
49
+ * @return {string} The interpolated string
50
+ */
51
+ function interpolateString(value, env) {
52
+ return value.replace(VAR_PATTERN, (_match, name, hasDefault, fallback) => {
53
+ const current = env[name];
54
+ if (current !== undefined && current !== "") {
55
+ return current;
56
+ }
57
+ if (hasDefault !== undefined) {
58
+ return fallback;
59
+ }
60
+ throw new Error(`references undefined environment variable \${${name}} and no default was given`);
61
+ });
62
+ }
63
+ /**
64
+ * Tells whether `${...}` may appear at a key path. `db.*` matches `db` and
65
+ * everything below it; `*` alone matches every key.
66
+ *
67
+ * @param {string} path - The key path of the value
68
+ * @param {string[]} allowedPaths - The allowed key path patterns
69
+ * @return {boolean} true when the path is allowed
70
+ */
71
+ function isAllowed(path, allowedPaths) {
72
+ return allowedPaths.some((pattern) => {
73
+ if (pattern === "*")
74
+ return true;
75
+ if (!pattern.endsWith(".*"))
76
+ return path === pattern;
77
+ const prefix = pattern.slice(0, -2);
78
+ return path === prefix || path.startsWith(`${prefix}.`);
79
+ });
80
+ }
81
+ /**
82
+ * Interpolates a value and everything below it.
83
+ *
84
+ * @param {unknown} input - The value to walk
85
+ * @param {Env} env - The environment to read variables from
86
+ * @param {string[]} allowedPaths - The allowed key paths, if any
87
+ * @param {string} path - The key path of the value
88
+ * @return {unknown} A copy of the value with references resolved
89
+ */
90
+ function walk(input, env, allowedPaths, path) {
91
+ if (typeof input === "string") {
92
+ if (!HAS_REFERENCE.test(input)) {
93
+ return input;
94
+ }
95
+ const where = path || "(root)";
96
+ if (allowedPaths && !isAllowed(path, allowedPaths)) {
97
+ throw new Error(`${where}: \${...} is only allowed at ${allowedPaths.join(", ") || "no key path here"}`);
98
+ }
99
+ try {
100
+ return interpolateString(input, env);
101
+ }
102
+ catch (e) {
103
+ throw new Error(`${where}: ${e.message}`);
104
+ }
105
+ }
106
+ if (Array.isArray(input)) {
107
+ return input.map((item, index) => walk(item, env, allowedPaths, `${path}[${index}]`));
108
+ }
109
+ if (input !== null && typeof input === "object") {
110
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [
111
+ key,
112
+ walk(value, env, allowedPaths, path ? `${path}.${key}` : key)
113
+ ]));
114
+ }
115
+ return input;
116
+ }
117
+ /**
118
+ * Returns a copy of a parsed config with `${VAR}` and `${VAR:-default}`
119
+ * references in its strings resolved from `env`. The input is not mutated.
120
+ * Errors name the key path where they happened.
121
+ *
122
+ * @param {InterpolateEnvParams} params - The config, env and allowed paths
123
+ * @return {T} A copy of the config with references resolved
124
+ * @throws {ValidationError} When the params are invalid
125
+ */
126
+ function interpolateEnv(params) {
127
+ const parsed = exports.interpolateEnvSchema.safeParse(params);
128
+ if (!parsed.success) {
129
+ throw new validation_error_1.ValidationError(parsed.error);
130
+ }
131
+ const { env, allowedPaths } = parsed.data;
132
+ return walk(params.input, env, allowedPaths, "");
133
+ }
@@ -0,0 +1,22 @@
1
+ import { z } from "zod/v4";
2
+ type ReadFile = (path: string) => string;
3
+ export declare const resolveSecretRefsSchema: z.ZodObject<{
4
+ input: z.ZodUnknown;
5
+ env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
6
+ secretsDir: z.ZodOptional<z.ZodString>;
7
+ readFile: z.ZodOptional<z.ZodCustom<ReadFile, ReadFile>>;
8
+ }, z.core.$strip>;
9
+ export type ResolveSecretRefsParams<T> = Omit<z.infer<typeof resolveSecretRefsSchema>, "input"> & {
10
+ input: T;
11
+ };
12
+ /**
13
+ * Returns a copy of a parsed config with every `secret://` value resolved.
14
+ * Errors name the key path and the reference
15
+ * (`db.url: secret://env/DB: environment variable DB is not set`).
16
+ *
17
+ * @param {ResolveSecretRefsParams} params - The config and resolve options
18
+ * @return {T} A copy of the config with references resolved
19
+ * @throws {ValidationError} When the params are invalid
20
+ */
21
+ export declare function resolveSecretRefs<T>(params: ResolveSecretRefsParams<T>): T;
22
+ export {};
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveSecretRefsSchema = void 0;
4
+ exports.resolveSecretRefs = resolveSecretRefs;
5
+ /*
6
+ * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster/routr
8
+ *
9
+ * This file is part of Routr.
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const fs_1 = require("fs");
24
+ const path_1 = require("path");
25
+ const v4_1 = require("zod/v4");
26
+ const validation_error_1 = require("../validation_error");
27
+ /**
28
+ * `secret://` references in config values. A string value that is exactly a
29
+ * reference is replaced by the secret it names, so YAML never holds the raw
30
+ * secret:
31
+ *
32
+ * secret://env/NAME the environment variable NAME
33
+ * secret://file/<absolute path> a file's contents
34
+ * secret://k8s/<secret>#<key> a Kubernetes Secret mounted as a volume,
35
+ * secret://k8s/<ns>/<secret>#<key> read from <secretsDir>/<secret>/<key>
36
+ * (default ROUTR_SECRETS_DIR or
37
+ * /var/run/routr/secrets). The namespace,
38
+ * when given, must be the pod's
39
+ * (POD_NAMESPACE) if that is known.
40
+ *
41
+ * File contents lose one trailing newline. Errors name the key path and the
42
+ * reference, never a value. Values that only contain `secret://` somewhere
43
+ * else are left alone.
44
+ */
45
+ const SECRET_PREFIX = "secret://";
46
+ const DEFAULT_SECRETS_DIR = "/var/run/routr/secrets";
47
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
48
+ const K8S_NAME = /^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$/;
49
+ const K8S_KEY = /^[-._a-zA-Z0-9]+$/;
50
+ exports.resolveSecretRefsSchema = v4_1.z.object({
51
+ input: v4_1.z.unknown(),
52
+ env: v4_1.z
53
+ .record(v4_1.z.string(), v4_1.z.string({ error: "env values must be strings" }).optional(), { error: "env must be an object of environment variables" })
54
+ .optional(),
55
+ secretsDir: v4_1.z
56
+ .string({ error: "secretsDir must be a directory path" })
57
+ .optional(),
58
+ readFile: v4_1.z
59
+ .custom((value) => typeof value === "function", {
60
+ error: "readFile must be a function"
61
+ })
62
+ .optional()
63
+ });
64
+ /**
65
+ * Tells whether a value is a `secret://` reference.
66
+ *
67
+ * @param {unknown} value - The value to check
68
+ * @return {boolean} true when the value is a reference
69
+ */
70
+ function isSecretRef(value) {
71
+ return typeof value === "string" && value.startsWith(SECRET_PREFIX);
72
+ }
73
+ /**
74
+ * Reads a secret file, dropping one trailing newline.
75
+ *
76
+ * @param {string} ref - The reference being resolved
77
+ * @param {string} path - The file to read
78
+ * @param {Options} options - The resolve options
79
+ * @return {string} The file's contents
80
+ */
81
+ function readSecretFile(ref, path, options) {
82
+ var _a;
83
+ const read = (_a = options.readFile) !== null && _a !== void 0 ? _a : ((p) => (0, fs_1.readFileSync)(p, { encoding: "utf8" }));
84
+ try {
85
+ return read(path).replace(/\r?\n$/, "");
86
+ }
87
+ catch (e) {
88
+ const code = e.code;
89
+ throw new Error(`${ref}: cannot read ${path}${code ? ` (${code})` : ""}`);
90
+ }
91
+ }
92
+ /**
93
+ * Resolves one `secret://` reference. Throws with a message that never
94
+ * contains the secret.
95
+ *
96
+ * @param {string} ref - The reference to resolve
97
+ * @param {Options} options - The resolve options
98
+ * @return {string} The secret
99
+ */
100
+ function resolveSecretRef(ref, options) {
101
+ var _a, _b;
102
+ const env = options.env;
103
+ const rest = ref.slice(SECRET_PREFIX.length);
104
+ const slash = rest.indexOf("/");
105
+ const kind = slash < 0 ? rest : rest.slice(0, slash);
106
+ const target = slash < 0 ? "" : rest.slice(slash + 1);
107
+ if (kind === "env") {
108
+ if (!NAME.test(target))
109
+ throw new Error(`invalid variable name in ${ref}`);
110
+ const value = env[target];
111
+ if (value === undefined || value === "")
112
+ throw new Error(`${ref}: environment variable ${target} is not set`);
113
+ return value;
114
+ }
115
+ if (kind === "file") {
116
+ if (!target)
117
+ throw new Error(`${ref}: missing file path`);
118
+ return readSecretFile(ref, (0, path_1.resolve)("/", target), options);
119
+ }
120
+ if (kind === "k8s") {
121
+ const hash = target.indexOf("#");
122
+ if (hash < 0)
123
+ throw new Error(`${ref}: missing #<key>`);
124
+ const parts = target.slice(0, hash).split("/");
125
+ const key = target.slice(hash + 1);
126
+ if (parts.length > 2 || !parts.every((p) => K8S_NAME.test(p)))
127
+ throw new Error(`${ref}: expected secret://k8s/[<namespace>/]<secret>#<key>`);
128
+ if (!K8S_KEY.test(key))
129
+ throw new Error(`${ref}: invalid key`);
130
+ const [namespace, name] = parts.length === 2 ? parts : [undefined, parts[0]];
131
+ const podNamespace = env.POD_NAMESPACE;
132
+ if (namespace && podNamespace && namespace !== podNamespace)
133
+ throw new Error(`${ref}: Secrets of namespace ${namespace} are not mounted here (${podNamespace})`);
134
+ const dir = (_b = (_a = options.secretsDir) !== null && _a !== void 0 ? _a : env.ROUTR_SECRETS_DIR) !== null && _b !== void 0 ? _b : DEFAULT_SECRETS_DIR;
135
+ const base = (0, path_1.isAbsolute)(dir) ? dir : (0, path_1.resolve)(dir);
136
+ return readSecretFile(ref, (0, path_1.join)(base, name, key), options);
137
+ }
138
+ throw new Error(`unsupported reference ${ref} (use secret://env/NAME, secret://file/<path> or secret://k8s/<secret>#<key>)`);
139
+ }
140
+ /**
141
+ * Resolves the references in a value and everything below it.
142
+ *
143
+ * @param {unknown} input - The value to walk
144
+ * @param {Options} options - The resolve options
145
+ * @param {string} path - The key path of the value
146
+ * @return {unknown} A copy of the value with references resolved
147
+ */
148
+ function walk(input, options, path) {
149
+ if (isSecretRef(input)) {
150
+ try {
151
+ return resolveSecretRef(input, options);
152
+ }
153
+ catch (e) {
154
+ throw new Error(`${path || "(root)"}: ${e.message}`);
155
+ }
156
+ }
157
+ if (Array.isArray(input)) {
158
+ return input.map((item, i) => walk(item, options, `${path}[${i}]`));
159
+ }
160
+ if (input !== null && typeof input === "object") {
161
+ return Object.fromEntries(Object.entries(input).map(([k, v]) => [
162
+ k,
163
+ walk(v, options, path ? `${path}.${k}` : k)
164
+ ]));
165
+ }
166
+ return input;
167
+ }
168
+ /**
169
+ * Returns a copy of a parsed config with every `secret://` value resolved.
170
+ * Errors name the key path and the reference
171
+ * (`db.url: secret://env/DB: environment variable DB is not set`).
172
+ *
173
+ * @param {ResolveSecretRefsParams} params - The config and resolve options
174
+ * @return {T} A copy of the config with references resolved
175
+ * @throws {ValidationError} When the params are invalid
176
+ */
177
+ function resolveSecretRefs(params) {
178
+ const parsed = exports.resolveSecretRefsSchema.safeParse(params);
179
+ if (!parsed.success) {
180
+ throw new validation_error_1.ValidationError(parsed.error);
181
+ }
182
+ const { env, secretsDir, readFile } = parsed.data;
183
+ return walk(params.input, { env: env !== null && env !== void 0 ? env : process.env, secretsDir, readFile }, "");
184
+ }
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { ValidationError } from "./validation_error";
1
2
  /**
2
3
  * Error thrown if the definition for a service is not found.
3
4
  */
package/dist/errors.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.BadRequestError = exports.ResourceAlreadyExistsError = exports.ResourceNotFoundError = exports.UnimplementedError = exports.ClientConnectionError = exports.ServiceUnavailableError = exports.NoListeningPointError = exports.ServiceDefinitionNotFoundError = void 0;
36
+ exports.BadRequestError = exports.ResourceAlreadyExistsError = exports.ResourceNotFoundError = exports.UnimplementedError = exports.ClientConnectionError = exports.ServiceUnavailableError = exports.NoListeningPointError = exports.ServiceDefinitionNotFoundError = exports.ValidationError = void 0;
37
37
  /*
38
38
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
39
39
  * http://github.com/fonoster/routr
@@ -53,6 +53,8 @@ exports.BadRequestError = exports.ResourceAlreadyExistsError = exports.ResourceN
53
53
  * limitations under the License.
54
54
  */
55
55
  const grpc = __importStar(require("@grpc/grpc-js"));
56
+ var validation_error_1 = require("./validation_error");
57
+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.ValidationError; } });
56
58
  /**
57
59
  * Error thrown if the definition for a service is not found.
58
60
  */
@@ -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,3 +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";
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.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,3 +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"));
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.
@@ -0,0 +1,35 @@
1
+ import type { z } from "zod/v4";
2
+ export interface FieldError {
3
+ field: string;
4
+ message: string;
5
+ code: string;
6
+ }
7
+ /**
8
+ * Custom error class that wraps Zod validation errors with structured details.
9
+ * Provides field-level errors suitable for API responses.
10
+ */
11
+ export declare class ValidationError extends Error {
12
+ readonly code = "VALIDATION_ERROR";
13
+ readonly fieldErrors: FieldError[];
14
+ readonly zodError: z.ZodError;
15
+ /**
16
+ * Constructs a new ValidationError.
17
+ *
18
+ * @param {z.ZodError} zodError - The error Zod returned
19
+ */
20
+ constructor(zodError: z.ZodError);
21
+ /**
22
+ * Extracts field-level errors from a ZodError for API responses.
23
+ *
24
+ * @param {z.ZodError} zodError - The error Zod returned
25
+ * @return {FieldError[]} One entry per failed field
26
+ */
27
+ private static extractFieldErrors;
28
+ /**
29
+ * Builds a single human-readable message from the field errors.
30
+ *
31
+ * @param {FieldError[]} fieldErrors - The failed fields
32
+ * @return {string} The message
33
+ */
34
+ private static formatMessage;
35
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ValidationError = void 0;
4
+ /**
5
+ * Custom error class that wraps Zod validation errors with structured details.
6
+ * Provides field-level errors suitable for API responses.
7
+ */
8
+ class ValidationError extends Error {
9
+ /**
10
+ * Constructs a new ValidationError.
11
+ *
12
+ * @param {z.ZodError} zodError - The error Zod returned
13
+ */
14
+ constructor(zodError) {
15
+ const fieldErrors = ValidationError.extractFieldErrors(zodError);
16
+ const message = ValidationError.formatMessage(fieldErrors);
17
+ super(message);
18
+ this.code = "VALIDATION_ERROR";
19
+ this.name = "ValidationError";
20
+ this.zodError = zodError;
21
+ this.fieldErrors = fieldErrors;
22
+ // Maintains proper stack trace for where error was thrown (V8 engines)
23
+ if (Error.captureStackTrace) {
24
+ Error.captureStackTrace(this, ValidationError);
25
+ }
26
+ }
27
+ /**
28
+ * Extracts field-level errors from a ZodError for API responses.
29
+ *
30
+ * @param {z.ZodError} zodError - The error Zod returned
31
+ * @return {FieldError[]} One entry per failed field
32
+ */
33
+ static extractFieldErrors(zodError) {
34
+ return zodError.issues.map((issue) => ({
35
+ field: issue.path.join("."),
36
+ message: issue.message,
37
+ code: issue.code
38
+ }));
39
+ }
40
+ /**
41
+ * Builds a single human-readable message from the field errors.
42
+ *
43
+ * @param {FieldError[]} fieldErrors - The failed fields
44
+ * @return {string} The message
45
+ */
46
+ static formatMessage(fieldErrors) {
47
+ if (fieldErrors.length === 0)
48
+ return "Validation failed";
49
+ return fieldErrors
50
+ .map((e) => (e.field ? `${e.field}: ${e.message}` : e.message))
51
+ .join("; ");
52
+ }
53
+ }
54
+ exports.ValidationError = ValidationError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/common",
3
- "version": "2.25.4",
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",
@@ -38,7 +38,8 @@
38
38
  "js-yaml": "^4.1.1",
39
39
  "pb-util": "^1.0.3",
40
40
  "phone": "^3.1.68",
41
- "validator": "^13.15.26"
41
+ "validator": "^13.15.26",
42
+ "zod": "^3.25.76"
42
43
  },
43
44
  "directories": {
44
45
  "src": "src",
@@ -60,5 +61,5 @@
60
61
  "devDependencies": {
61
62
  "@types/js-yaml": "^4.0.5"
62
63
  },
63
- "gitHead": "f7beda69ae61bebeec98b534faf81e22ae7d40dc"
64
+ "gitHead": "826c897ddd664991f4c6376bae37838c0b5cd362"
64
65
  }