@crewhaus/tool-notify 0.7.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,42 @@
1
+ import { CrewhausError } from "@crewhaus/errors";
2
+ /** Raised when a caller-supplied path resolves outside the workspace root. */
3
+ export declare class ToolPermissionError extends CrewhausError {
4
+ readonly name = "ToolPermissionError";
5
+ readonly toolName: string;
6
+ readonly path: string;
7
+ constructor(toolName: string, attemptedPath: string);
8
+ }
9
+ /**
10
+ * A validated path, in both forms the tools need.
11
+ *
12
+ * `real` has every in-workspace symlink already resolved and is what I/O
13
+ * should use — operating on it closes most of the check-to-use window.
14
+ * `abs` is the lexical resolution, which is what a tool must use when the
15
+ * question is about the link ITSELF (`Stat` reporting a symlink target,
16
+ * `RemovePath` deleting a link rather than its destination).
17
+ */
18
+ export type SafePath = {
19
+ readonly abs: string;
20
+ readonly real: string;
21
+ /** The path as the caller wrote it, for echoing back in results. */
22
+ readonly given: string;
23
+ /** Slash-separated path relative to the workspace root. */
24
+ readonly rel: string;
25
+ };
26
+ /** The workspace root, resolved. Every path is contained within it. */
27
+ export declare function workspaceRoot(): string;
28
+ export declare function resolveSafe(toolName: string, rel: string, root?: string): SafePath;
29
+ /** A path relative to the workspace root, with `/` separators on every OS. */
30
+ export declare function toPosix(p: string): string;
31
+ /**
32
+ * True when `candidate` is `parent` or lives underneath it. Both must already
33
+ * be absolute. Used to keep an archive entry, or a symlink inside an
34
+ * extracted tree, from reaching outside its destination.
35
+ */
36
+ export declare function isInside(parent: string, candidate: string): boolean;
37
+ /**
38
+ * Reject an archive member name that would escape its destination: an
39
+ * absolute path, a Windows drive prefix, or any `..` segment. Checked on the
40
+ * NAME, before extraction, because after extraction the damage is done.
41
+ */
42
+ export declare function archiveEntryEscapes(name: string): boolean;
package/dist/paths.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Path containment — the gate every caller-supplied path in this package
3
+ * passes through before any syscall touches it.
4
+ *
5
+ * The approach is the one `@crewhaus/tool-fs` uses, and for the same reasons:
6
+ * a lexical check alone is fooled by a symlink that lives inside the
7
+ * workspace and points outside it (CWE-59), so the real path is checked too.
8
+ * The workspace root is `process.cwd()`, matching tool-fs, so a harness that
9
+ * trusts one tool's boundary gets the same boundary here.
10
+ */
11
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
12
+ import * as path from "node:path";
13
+ import { CrewhausError } from "@crewhaus/errors";
14
+ /** Raised when a caller-supplied path resolves outside the workspace root. */
15
+ export class ToolPermissionError extends CrewhausError {
16
+ name = "ToolPermissionError";
17
+ toolName;
18
+ path;
19
+ constructor(toolName, attemptedPath) {
20
+ super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
21
+ this.toolName = toolName;
22
+ this.path = attemptedPath;
23
+ }
24
+ }
25
+ /** The workspace root, resolved. Every path is contained within it. */
26
+ export function workspaceRoot() {
27
+ return path.resolve(process.cwd());
28
+ }
29
+ /**
30
+ * Resolve `rel` inside the workspace, or throw `ToolPermissionError`.
31
+ *
32
+ * The leaf is allowed not to exist — every tool here that creates something
33
+ * needs to validate a destination before it is made — so the deepest
34
+ * EXISTING ancestor is realpath'd and the missing tail re-appended. Any
35
+ * failure other than that walk fails closed.
36
+ */
37
+ /**
38
+ * True when the NAME exists, whether or not it leads anywhere.
39
+ *
40
+ * `existsSync` FOLLOWS symlinks, so it answers false for a link whose target
41
+ * is missing — and that is exactly the case that matters: a dangling link is
42
+ * still a door, because `open(…, "w")` through `evil -> /outside/x` CREATES
43
+ * `/outside/x`. Probing with `lstat` keeps the link's name in the part of the
44
+ * path that gets resolved, rather than in the "does not exist yet" tail that
45
+ * is re-appended to the root verbatim and so passes the containment check.
46
+ */
47
+ function nameExists(p) {
48
+ try {
49
+ lstatSync(p);
50
+ return true;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ /**
57
+ * Where `target` would actually land, with every symlink on the way already
58
+ * followed — including one whose own target does not exist yet.
59
+ *
60
+ * `realpathSync` gives up with ENOENT on a dangling link, which would leave
61
+ * that link unresolved and let it stand in for a plain missing file. So the
62
+ * deepest ancestor that exists as a NAME is resolved, a dangling one is
63
+ * followed a hop by hand, and the components that do not exist are appended.
64
+ * The result is the path an `open` would create, which is the only path worth
65
+ * checking containment against.
66
+ */
67
+ function resolveLocation(target, depth = 0) {
68
+ if (depth > 40)
69
+ throw new Error(`symlink chain at "${target}" is too long to resolve`);
70
+ let probe = target;
71
+ const tail = [];
72
+ while (!nameExists(probe)) {
73
+ tail.unshift(path.basename(probe));
74
+ const parent = path.dirname(probe);
75
+ if (parent === probe)
76
+ break; // reached the filesystem root
77
+ probe = parent;
78
+ }
79
+ let probeReal;
80
+ try {
81
+ probeReal = realpathSync(probe);
82
+ }
83
+ catch (err) {
84
+ if (err.code !== "ENOENT")
85
+ throw err;
86
+ // The name is there but `realpath` cannot finish it: a symlink with a
87
+ // missing target. `readlinkSync` throws EINVAL on anything else, which
88
+ // fails closed.
89
+ const link = readlinkSync(probe);
90
+ // A RELATIVE target resolves against the directory that actually CONTAINS
91
+ // the link, which is not the link's lexical parent when that parent is
92
+ // itself reached through a symlink. `<root>/dirlink/x -> ../y` with
93
+ // `dirlink` pointing out of the root really lands at `<elsewhere>/y`, but
94
+ // measured from the lexical parent it reads as `<root>/y` — an in-root
95
+ // path the caller's path does not lead to. So the parent is made real
96
+ // first. An absolute target ignores the base.
97
+ const base = realpathSync(path.dirname(probe));
98
+ probeReal = resolveLocation(path.resolve(base, link), depth + 1);
99
+ }
100
+ return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
101
+ }
102
+ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
103
+ const rootResolved = path.resolve(root);
104
+ const abs = path.resolve(rootResolved, rel);
105
+ // 1) Lexical containment — rejects `..` and absolute escapes. The trailing
106
+ // separator avoids the `/root` vs `/root-sibling` prefix pitfall.
107
+ if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
108
+ throw new ToolPermissionError(toolName, rel);
109
+ }
110
+ let real;
111
+ try {
112
+ const rootReal = realpathSync(rootResolved);
113
+ real = resolveLocation(abs);
114
+ // 2) Symlink-aware containment. The real path must land inside the real
115
+ // root, so an in-workspace symlink pointing at /etc is refused here.
116
+ if (real !== rootReal && !real.startsWith(`${rootReal}${path.sep}`)) {
117
+ throw new ToolPermissionError(toolName, rel);
118
+ }
119
+ }
120
+ catch (err) {
121
+ if (err instanceof ToolPermissionError)
122
+ throw err;
123
+ throw new ToolPermissionError(toolName, rel);
124
+ }
125
+ return {
126
+ abs,
127
+ real,
128
+ given: rel,
129
+ rel: toPosix(path.relative(rootResolved, abs)),
130
+ };
131
+ }
132
+ /** A path relative to the workspace root, with `/` separators on every OS. */
133
+ export function toPosix(p) {
134
+ return path.sep === "/" ? p : p.split(path.sep).join("/");
135
+ }
136
+ /**
137
+ * True when `candidate` is `parent` or lives underneath it. Both must already
138
+ * be absolute. Used to keep an archive entry, or a symlink inside an
139
+ * extracted tree, from reaching outside its destination.
140
+ */
141
+ export function isInside(parent, candidate) {
142
+ const p = path.resolve(parent);
143
+ const c = path.resolve(candidate);
144
+ return c === p || c.startsWith(`${p}${path.sep}`);
145
+ }
146
+ /**
147
+ * Reject an archive member name that would escape its destination: an
148
+ * absolute path, a Windows drive prefix, or any `..` segment. Checked on the
149
+ * NAME, before extraction, because after extraction the damage is done.
150
+ */
151
+ export function archiveEntryEscapes(name) {
152
+ const normalized = name.replace(/\\/g, "/");
153
+ if (normalized.startsWith("/"))
154
+ return true;
155
+ if (/^[A-Za-z]:/.test(normalized))
156
+ return true;
157
+ return normalized.split("/").some((segment) => segment === "..");
158
+ }
package/dist/smtp.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ export type SmtpReply = {
2
+ readonly code: number;
3
+ readonly lines: readonly string[];
4
+ };
5
+ export type SmtpOptions = {
6
+ readonly host: string;
7
+ readonly port: number;
8
+ /** The address vetted by the SSRF gate; the socket dials this, not `host`. */
9
+ readonly pinnedIp: string;
10
+ /** True for implicit TLS (port 465). False starts plain and may STARTTLS. */
11
+ readonly implicitTls: boolean;
12
+ /** Refuse to continue in the clear. Default true at the call site. */
13
+ readonly requireTls: boolean;
14
+ /** Rejects an untrusted certificate. Only a test has a reason to relax it. */
15
+ readonly rejectUnauthorized: boolean;
16
+ readonly username?: string | undefined;
17
+ /** Already resolved from an environment variable NAME by the caller. */
18
+ readonly password?: string | undefined;
19
+ readonly authMethod?: "plain" | "login" | "auto" | undefined;
20
+ /** The name the client announces in EHLO. */
21
+ readonly ehloName: string;
22
+ readonly envelopeFrom: string;
23
+ readonly envelopeTo: readonly string[];
24
+ /** The complete RFC 5322 message, not yet dot-stuffed. */
25
+ readonly message: string;
26
+ readonly signal: AbortSignal;
27
+ /** Cap on a single reply, and on what is buffered while reading one. */
28
+ readonly maxReplyBytes: number;
29
+ };
30
+ export type SmtpOutcome = {
31
+ readonly ok: true;
32
+ readonly secured: boolean;
33
+ readonly authenticated: boolean;
34
+ readonly accepted: readonly string[];
35
+ readonly rejected: ReadonlyArray<{
36
+ readonly address: string;
37
+ readonly reply: string;
38
+ }>;
39
+ /** The server's reply to the final dot — where a queue id usually is. */
40
+ readonly queued: string;
41
+ readonly transcript: readonly string[];
42
+ readonly capabilities: readonly string[];
43
+ } | {
44
+ readonly ok: false;
45
+ readonly error: string;
46
+ readonly transcript: readonly string[];
47
+ };
48
+ /**
49
+ * Run one session and deliver one message.
50
+ *
51
+ * Never throws: a protocol failure, a refused recipient and a blown deadline
52
+ * all come back as an outcome, with the transcript so far, because the
53
+ * transcript is what makes an SMTP problem diagnosable without a packet
54
+ * capture.
55
+ */
56
+ export declare function sendMail(options: SmtpOptions): Promise<SmtpOutcome>;