@landstrip/landstrip-api 0.18.39
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/LICENSE +201 -0
- package/README.md +64 -0
- package/bin/landstrip.js +33 -0
- package/lib/index.d.ts +151 -0
- package/lib/index.js +72 -0
- package/lib/proxy.d.ts +24 -0
- package/lib/proxy.js +304 -0
- package/lib/shared.d.ts +57 -0
- package/lib/shared.js +299 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# landstrip
|
|
2
|
+
|
|
3
|
+
`landstrip` runs commands in an OS-level sandbox using Landlock on Linux,
|
|
4
|
+
Seatbelt on macOS, and AppContainer or restricted users on Windows.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install --save-dev @landstrip/landstrip-api
|
|
10
|
+
npx landstrip run -p policy.json -- cargo test
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The npm package installs a Node.js wrapper and a native binary for the current
|
|
14
|
+
platform.
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
landstrip run -p policy.json -- cargo test
|
|
20
|
+
landstrip policy validate -p policy.json
|
|
21
|
+
landstrip policy resolve -p policy.json
|
|
22
|
+
landstrip doctor
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Run `landstrip --help` or see [landstrip(1)](../landstrip/man/man1/landstrip.1) for the full
|
|
26
|
+
command reference.
|
|
27
|
+
|
|
28
|
+
## Agent extensions
|
|
29
|
+
|
|
30
|
+
| Integration | Package | Documentation |
|
|
31
|
+
| ----------- | ---------------------- | -------------------------------------------------------------------- |
|
|
32
|
+
| OpenCode | `opencode-landstrip` | [OpenCode](packages/opencode-landstrip/README.md) |
|
|
33
|
+
| Pi | `pi-landstrip` | [Pi](packages/pi-landstrip/README.md) |
|
|
34
|
+
|
|
35
|
+
## Policy
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
{
|
|
39
|
+
"filesystem": {
|
|
40
|
+
"allowWrite": ["."],
|
|
41
|
+
"denyWrite": ["**/.env", "**/*.pem"],
|
|
42
|
+
"denyRead": ["~/.ssh"],
|
|
43
|
+
"allowRead": ["~/.ssh/config"]
|
|
44
|
+
},
|
|
45
|
+
"network": {
|
|
46
|
+
"allowNetwork": false,
|
|
47
|
+
"allowLocalBinding": false
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Pass policies with `-p, --policy <FILE>`. Later policies merge over earlier
|
|
53
|
+
ones. Platform behavior and limits are documented in the manual.
|
|
54
|
+
|
|
55
|
+
## Development
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
make ci
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Licensing
|
|
62
|
+
|
|
63
|
+
`@landstrip/landstrip-api` is licensed under the Apache 2.0 license. See
|
|
64
|
+
[LICENSE](LICENSE) for more information.
|
package/bin/landstrip.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const { spawn } = require('node:child_process');
|
|
6
|
+
const { binaryPath } = require('../lib');
|
|
7
|
+
|
|
8
|
+
let child;
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
child = spawn(binaryPath(), process.argv.slice(2), { stdio: 'inherit' });
|
|
12
|
+
} catch (error) {
|
|
13
|
+
console.error(error.message);
|
|
14
|
+
process.exit(1);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
child.on('error', (error) => {
|
|
18
|
+
console.error(error.message);
|
|
19
|
+
process.exit(1);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
child.on('exit', (code, signal) => {
|
|
23
|
+
if (signal) {
|
|
24
|
+
if (process.platform === 'win32') {
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
process.kill(process.pid, signal);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
process.exit(code === null ? 1 : code);
|
|
33
|
+
});
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
/** The kernel layer an event is attributed to. */
|
|
4
|
+
export type LandstripMechanism =
|
|
5
|
+
| 'landlock'
|
|
6
|
+
| 'seccomp'
|
|
7
|
+
| 'seatbelt'
|
|
8
|
+
| 'appcontainer';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `query` holds the syscall until the launcher answers with a
|
|
12
|
+
* {@link LandstripControlResponse}; `info` is terminal. Queries need a socket on
|
|
13
|
+
* `--trap-fd`, and only the Linux broker raises them.
|
|
14
|
+
*/
|
|
15
|
+
export type LandstripTrapState = 'query' | 'info';
|
|
16
|
+
|
|
17
|
+
/** Why a filesystem access was mediated. */
|
|
18
|
+
export type LandstripTrapReason = 'allow_miss' | 'deny_match';
|
|
19
|
+
|
|
20
|
+
export interface LandstripProcess {
|
|
21
|
+
pid: number;
|
|
22
|
+
exe: string | null;
|
|
23
|
+
cwd: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A filesystem access the policy denies. */
|
|
27
|
+
export interface LandstripFilesystemTrap {
|
|
28
|
+
kind: 'filesystem';
|
|
29
|
+
code: 'FILESYSTEM_DENIED';
|
|
30
|
+
state: LandstripTrapState;
|
|
31
|
+
/** Decimal `u64`; `"0"` marks a terminal `info` event. */
|
|
32
|
+
query_id: string;
|
|
33
|
+
operation: 'read' | 'write';
|
|
34
|
+
/** The resolved path. */
|
|
35
|
+
path: string;
|
|
36
|
+
/** The path the tool asked for, before resolution. */
|
|
37
|
+
requested_path: string;
|
|
38
|
+
syscall: string;
|
|
39
|
+
errno: string;
|
|
40
|
+
flags: string[];
|
|
41
|
+
reason: LandstripTrapReason;
|
|
42
|
+
/** The policy edit that would permit this access. */
|
|
43
|
+
suggested_grant: { allowRead?: string; allowWrite?: string };
|
|
44
|
+
process: LandstripProcess;
|
|
45
|
+
mechanism: 'seccomp';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A network access the policy denies. */
|
|
49
|
+
export interface LandstripNetworkTrap {
|
|
50
|
+
kind: 'network';
|
|
51
|
+
code: 'NETWORK_DENIED';
|
|
52
|
+
state: LandstripTrapState;
|
|
53
|
+
/** Decimal `u64`; `"0"` marks a terminal `info` event. */
|
|
54
|
+
query_id: string;
|
|
55
|
+
operation: 'connect' | 'bind';
|
|
56
|
+
/** `address:port`. */
|
|
57
|
+
target: string;
|
|
58
|
+
syscall: string;
|
|
59
|
+
errno: string;
|
|
60
|
+
mechanism: 'seccomp';
|
|
61
|
+
process: LandstripProcess;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The sandbox was installed but the tool did not start. */
|
|
65
|
+
export interface LandstripLaunchTrap {
|
|
66
|
+
kind: 'launch';
|
|
67
|
+
code: 'LAUNCH_FAILED';
|
|
68
|
+
program: string;
|
|
69
|
+
/** Absent where the platform has no POSIX errno for the failure. */
|
|
70
|
+
errno?: string;
|
|
71
|
+
message: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The command line was rejected. Reaches stderr only; landstrip exits 2. */
|
|
75
|
+
export interface LandstripUsageTrap {
|
|
76
|
+
kind: 'usage';
|
|
77
|
+
code: 'USAGE_ERROR';
|
|
78
|
+
message: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A policy the platform sandbox cannot enforce, rejected before launch. */
|
|
82
|
+
export type LandstripPolicyErrorCode =
|
|
83
|
+
| 'POLICY_PARSE_FAILED'
|
|
84
|
+
| 'POLICY_IO_FAILED'
|
|
85
|
+
| 'POLICY_UNRESTRICTED_READ'
|
|
86
|
+
| 'POLICY_TCP_BIND_UNSUPPORTED'
|
|
87
|
+
| 'POLICY_UNIX_SOCKET_UNSUPPORTED'
|
|
88
|
+
| 'POLICY_UNIX_SOCKET_PATH'
|
|
89
|
+
| 'POLICY_DENY_WRITE_SYMLINK_ANCESTOR'
|
|
90
|
+
| 'POLICY_INVALID_PORT'
|
|
91
|
+
| 'POLICY_EMPTY_PATH'
|
|
92
|
+
| 'POLICY_HOME_UNAVAILABLE'
|
|
93
|
+
| 'POLICY_TRAVERSAL_DEPTH';
|
|
94
|
+
|
|
95
|
+
/** The stage that failed before the tool ran. */
|
|
96
|
+
export type LandstripInternalCode =
|
|
97
|
+
| LandstripPolicyErrorCode
|
|
98
|
+
| 'SANDBOX_SETUP_FAILED'
|
|
99
|
+
| 'SUPERVISE_FAILED'
|
|
100
|
+
| 'PLATFORM_UNSUPPORTED'
|
|
101
|
+
| 'INTEGER_TOO_LARGE'
|
|
102
|
+
| 'INTERNAL_ERROR';
|
|
103
|
+
|
|
104
|
+
/** Everything that fails before the tool runs. */
|
|
105
|
+
export type LandstripInternalTrap =
|
|
106
|
+
| {
|
|
107
|
+
kind: 'internal';
|
|
108
|
+
code: 'SANDBOX_SETUP_FAILED';
|
|
109
|
+
mechanism: LandstripMechanism;
|
|
110
|
+
message: string;
|
|
111
|
+
}
|
|
112
|
+
| {
|
|
113
|
+
kind: 'internal';
|
|
114
|
+
code: Exclude<LandstripInternalCode, 'SANDBOX_SETUP_FAILED'>;
|
|
115
|
+
mechanism?: never;
|
|
116
|
+
message: string;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* One landstrip event. Failure and completed-denial events are written to
|
|
121
|
+
* stderr; pending Linux query events are written only to `--trap-fd`.
|
|
122
|
+
*/
|
|
123
|
+
export type LandstripTrap =
|
|
124
|
+
| LandstripFilesystemTrap
|
|
125
|
+
| LandstripNetworkTrap
|
|
126
|
+
| LandstripLaunchTrap
|
|
127
|
+
| LandstripUsageTrap
|
|
128
|
+
| LandstripInternalTrap;
|
|
129
|
+
|
|
130
|
+
/** Every code landstrip reports, across all trap kinds. */
|
|
131
|
+
export type LandstripCode = LandstripTrap['code'];
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The answer to a `state: "query"` trap, written back to the trap socket as one
|
|
135
|
+
* JSON line. `query_id` is an opaque decimal `u64` copied verbatim from the
|
|
136
|
+
* trap. An unanswered query holds the sandboxed syscall.
|
|
137
|
+
*/
|
|
138
|
+
export interface LandstripControlResponse {
|
|
139
|
+
query_id: string;
|
|
140
|
+
action: 'allow' | 'deny';
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Path to the native landstrip binary for the running platform.
|
|
145
|
+
*
|
|
146
|
+
* @throws if the platform is unsupported, or the binary package is not installed.
|
|
147
|
+
*/
|
|
148
|
+
export function binaryPath(platform?: string, arch?: string): string;
|
|
149
|
+
|
|
150
|
+
/** Name of the binary package for the given platform. */
|
|
151
|
+
export function packageName(platform?: string, arch?: string): string;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
const packages = {
|
|
8
|
+
'darwin-arm64': {
|
|
9
|
+
packageName: '@landstrip/landstrip-darwin-arm64',
|
|
10
|
+
binary: 'bin/landstrip',
|
|
11
|
+
},
|
|
12
|
+
'darwin-x64': {
|
|
13
|
+
packageName: '@landstrip/landstrip-darwin-x64',
|
|
14
|
+
binary: 'bin/landstrip',
|
|
15
|
+
},
|
|
16
|
+
'linux-x64': {
|
|
17
|
+
packageName: '@landstrip/landstrip-linux-x64',
|
|
18
|
+
binary: 'bin/landstrip',
|
|
19
|
+
},
|
|
20
|
+
'linux-arm64': {
|
|
21
|
+
packageName: '@landstrip/landstrip-linux-arm64',
|
|
22
|
+
binary: 'bin/landstrip',
|
|
23
|
+
},
|
|
24
|
+
'win32-x64': {
|
|
25
|
+
packageName: '@landstrip/landstrip-win32-x64',
|
|
26
|
+
binary: 'bin/landstrip.exe',
|
|
27
|
+
},
|
|
28
|
+
'win32-arm64': {
|
|
29
|
+
packageName: '@landstrip/landstrip-win32-arm64',
|
|
30
|
+
binary: 'bin/landstrip.exe',
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function target(platform = process.platform, arch = process.arch) {
|
|
35
|
+
const key = `${platform}-${arch}`;
|
|
36
|
+
const value = packages[key];
|
|
37
|
+
|
|
38
|
+
if (!value) {
|
|
39
|
+
throw new Error(`Unsupported landstrip platform: ${platform} ${arch}`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function packageName(platform = process.platform, arch = process.arch) {
|
|
46
|
+
return target(platform, arch).packageName;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function binaryPath(platform = process.platform, arch = process.arch) {
|
|
50
|
+
const value = target(platform, arch);
|
|
51
|
+
let manifest;
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
manifest = require.resolve(`${value.packageName}/package.json`);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`The landstrip binary package ${value.packageName} is not installed. ` +
|
|
58
|
+
'Reinstall @landstrip/landstrip-api with optional dependencies enabled.'
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const resolved = path.join(path.dirname(manifest), value.binary);
|
|
63
|
+
|
|
64
|
+
if (!fs.statSync(resolved).isFile()) {
|
|
65
|
+
throw new Error(`landstrip binary not found at ${resolved}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return resolved;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
exports.binaryPath = binaryPath;
|
|
72
|
+
exports.packageName = packageName;
|
package/lib/proxy.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
export interface ProxyPortRange {
|
|
4
|
+
low: number;
|
|
5
|
+
high: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface FilterProxyOptions {
|
|
9
|
+
/** Gate for every proxied domain; may prompt interactively. */
|
|
10
|
+
isDomainAllowed(domain: string): boolean | Promise<boolean>;
|
|
11
|
+
/** Exact `Proxy-Authorization` header value required from clients. */
|
|
12
|
+
authorization?: string;
|
|
13
|
+
/** Inclusive listen port range; defaults to an ephemeral port. */
|
|
14
|
+
portRange?: ProxyPortRange;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface FilterProxyHandle {
|
|
18
|
+
port: number;
|
|
19
|
+
stop(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isPublicProxyAddress(address: string, family?: number): boolean;
|
|
23
|
+
|
|
24
|
+
export function startFilterProxy(options: FilterProxyOptions): Promise<FilterProxyHandle>;
|
package/lib/proxy.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { lookup } = require('node:dns/promises');
|
|
5
|
+
const { BlockList, connect, createServer, isIP } = require('node:net');
|
|
6
|
+
|
|
7
|
+
const prohibitedProxyAddresses = new BlockList();
|
|
8
|
+
|
|
9
|
+
for (const [network, prefix] of [
|
|
10
|
+
['0.0.0.0', 8],
|
|
11
|
+
['10.0.0.0', 8],
|
|
12
|
+
['100.64.0.0', 10],
|
|
13
|
+
['127.0.0.0', 8],
|
|
14
|
+
['169.254.0.0', 16],
|
|
15
|
+
['172.16.0.0', 12],
|
|
16
|
+
['192.0.0.0', 24],
|
|
17
|
+
['192.168.0.0', 16],
|
|
18
|
+
['198.18.0.0', 15],
|
|
19
|
+
['224.0.0.0', 4],
|
|
20
|
+
['240.0.0.0', 4],
|
|
21
|
+
]) {
|
|
22
|
+
prohibitedProxyAddresses.addSubnet(network, prefix, 'ipv4');
|
|
23
|
+
}
|
|
24
|
+
for (const [network, prefix] of [
|
|
25
|
+
['::', 128],
|
|
26
|
+
['::1', 128],
|
|
27
|
+
['fc00::', 7],
|
|
28
|
+
['fe80::', 10],
|
|
29
|
+
['ff00::', 8],
|
|
30
|
+
]) {
|
|
31
|
+
prohibitedProxyAddresses.addSubnet(network, prefix, 'ipv6');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function parseProxyPort(value, defaultPort) {
|
|
35
|
+
const rawPort = value ?? String(defaultPort);
|
|
36
|
+
if (!/^\d+$/.test(rawPort)) return null;
|
|
37
|
+
|
|
38
|
+
const port = Number(rawPort);
|
|
39
|
+
return port >= 1 && port <= 65535 ? port : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function splitHostPort(target, defaultPort) {
|
|
43
|
+
const bracketMatch = target.match(/^\[([^\]]+)\](?::(.*))?$/);
|
|
44
|
+
const host = bracketMatch?.[1];
|
|
45
|
+
if (host) {
|
|
46
|
+
const port = parseProxyPort(bracketMatch[2], defaultPort);
|
|
47
|
+
return port === null ? null : { host, port };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const lastColon = target.lastIndexOf(':');
|
|
51
|
+
if (lastColon > -1 && target.indexOf(':') === lastColon) {
|
|
52
|
+
const port = parseProxyPort(target.slice(lastColon + 1), defaultPort);
|
|
53
|
+
return port === null ? null : { host: target.slice(0, lastColon), port };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return { host: target, port: defaultPort };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function denyProxyRequest(client, status = '403 Forbidden') {
|
|
60
|
+
client.write(`HTTP/1.1 ${status}\r\nContent-Length: 0\r\n\r\n`);
|
|
61
|
+
client.end();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function isPublicProxyAddress(address, family = isIP(address)) {
|
|
65
|
+
if (family === 4) return !prohibitedProxyAddresses.check(address, 'ipv4');
|
|
66
|
+
if (family === 6) return !prohibitedProxyAddresses.check(address, 'ipv6');
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function resolveProxyEndpoint(host) {
|
|
71
|
+
const literalFamily = isIP(host);
|
|
72
|
+
if (literalFamily === 4 || literalFamily === 6) {
|
|
73
|
+
if (!isPublicProxyAddress(host, literalFamily)) {
|
|
74
|
+
throw new Error(`Proxy destination is not public: ${host}`);
|
|
75
|
+
}
|
|
76
|
+
return { address: host, family: literalFamily };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const addresses = await lookup(host, { all: true, verbatim: true });
|
|
80
|
+
if (
|
|
81
|
+
addresses.length === 0 ||
|
|
82
|
+
addresses.some(({ address, family }) => !isPublicProxyAddress(address, family))
|
|
83
|
+
) {
|
|
84
|
+
throw new Error(`Proxy destination resolves to a non-public address: ${host}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const endpoint = addresses[0];
|
|
88
|
+
if (endpoint.family !== 4 && endpoint.family !== 6) {
|
|
89
|
+
throw new Error(`Proxy could not resolve destination: ${host}`);
|
|
90
|
+
}
|
|
91
|
+
return { address: endpoint.address, family: endpoint.family };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function pipeSockets(client, upstream, initialData) {
|
|
95
|
+
upstream.on('error', () => client.destroy());
|
|
96
|
+
client.on('error', () => upstream.destroy());
|
|
97
|
+
|
|
98
|
+
if (initialData?.length) upstream.write(initialData);
|
|
99
|
+
|
|
100
|
+
client.pipe(upstream);
|
|
101
|
+
upstream.pipe(client);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function startFilterProxy(options) {
|
|
105
|
+
const { isDomainAllowed, authorization, portRange } = options;
|
|
106
|
+
const sockets = new Set();
|
|
107
|
+
|
|
108
|
+
// Track the upstream socket so stop() tears it down, and abandon a still-
|
|
109
|
+
// connecting upstream when its client goes away — otherwise a connect to a
|
|
110
|
+
// black-holed host lingers in SYN-retry (~2 min), leaking an fd per request.
|
|
111
|
+
function trackUpstream(upstream, client, settled) {
|
|
112
|
+
sockets.add(upstream);
|
|
113
|
+
upstream.once('close', () => sockets.delete(upstream));
|
|
114
|
+
client.once('close', () => {
|
|
115
|
+
if (!settled()) upstream.destroy();
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function handleConnect(client, target, rest) {
|
|
120
|
+
const endpoint = splitHostPort(target, 443);
|
|
121
|
+
if (!endpoint) {
|
|
122
|
+
denyProxyRequest(client, '400 Bad Request');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!(await isDomainAllowed(endpoint.host))) {
|
|
127
|
+
denyProxyRequest(client);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const resolved = await resolveProxyEndpoint(endpoint.host);
|
|
132
|
+
let settled = false;
|
|
133
|
+
const upstream = connect(
|
|
134
|
+
{ host: resolved.address, port: endpoint.port, family: resolved.family },
|
|
135
|
+
() => {
|
|
136
|
+
settled = true;
|
|
137
|
+
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
138
|
+
pipeSockets(client, upstream, rest);
|
|
139
|
+
},
|
|
140
|
+
);
|
|
141
|
+
trackUpstream(upstream, client, () => settled);
|
|
142
|
+
upstream.once('error', () => {
|
|
143
|
+
if (settled) return;
|
|
144
|
+
settled = true;
|
|
145
|
+
denyProxyRequest(client, '502 Bad Gateway');
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function handleHttp(client, headerText, rest) {
|
|
150
|
+
const lines = headerText.split(/\r?\n/);
|
|
151
|
+
const requestLine = lines[0];
|
|
152
|
+
if (!requestLine) {
|
|
153
|
+
denyProxyRequest(client, '400 Bad Request');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const [method, rawTarget, version] = requestLine.split(' ');
|
|
158
|
+
if (!method || !rawTarget || !version) {
|
|
159
|
+
denyProxyRequest(client, '400 Bad Request');
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
let url;
|
|
164
|
+
try {
|
|
165
|
+
url = new URL(rawTarget);
|
|
166
|
+
} catch {
|
|
167
|
+
const host = lines
|
|
168
|
+
.find((line) => line.toLowerCase().startsWith('host:'))
|
|
169
|
+
?.slice(5)
|
|
170
|
+
.trim();
|
|
171
|
+
if (!host) {
|
|
172
|
+
denyProxyRequest(client, '400 Bad Request');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
url = new URL(`http://${host}${rawTarget}`);
|
|
178
|
+
} catch {
|
|
179
|
+
denyProxyRequest(client, '400 Bad Request');
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (!(await isDomainAllowed(url.hostname))) {
|
|
185
|
+
denyProxyRequest(client);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const port = parseProxyPort(url.port || undefined, url.protocol === 'https:' ? 443 : 80);
|
|
190
|
+
if (port === null) {
|
|
191
|
+
denyProxyRequest(client, '400 Bad Request');
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const path = `${url.pathname}${url.search}` || '/';
|
|
196
|
+
lines[0] = `${method} ${path} ${version}`;
|
|
197
|
+
|
|
198
|
+
const rewrittenHeader = lines
|
|
199
|
+
.filter(
|
|
200
|
+
(line) =>
|
|
201
|
+
!line.toLowerCase().startsWith('proxy-connection:') &&
|
|
202
|
+
!line.toLowerCase().startsWith('proxy-authorization:'),
|
|
203
|
+
)
|
|
204
|
+
.map((line) => (line.toLowerCase().startsWith('host:') ? `Host: ${url.host}` : line))
|
|
205
|
+
.join('\r\n');
|
|
206
|
+
const resolved = await resolveProxyEndpoint(url.hostname);
|
|
207
|
+
let settled = false;
|
|
208
|
+
const upstream = connect({ host: resolved.address, port, family: resolved.family }, () => {
|
|
209
|
+
settled = true;
|
|
210
|
+
upstream.write(`${rewrittenHeader}\r\n\r\n`);
|
|
211
|
+
pipeSockets(client, upstream, rest);
|
|
212
|
+
});
|
|
213
|
+
trackUpstream(upstream, client, () => settled);
|
|
214
|
+
upstream.once('error', () => {
|
|
215
|
+
if (settled) return;
|
|
216
|
+
settled = true;
|
|
217
|
+
denyProxyRequest(client, '502 Bad Gateway');
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function handleClient(client) {
|
|
222
|
+
sockets.add(client);
|
|
223
|
+
client.on('close', () => sockets.delete(client));
|
|
224
|
+
client.on('error', () => sockets.delete(client));
|
|
225
|
+
|
|
226
|
+
let buffered = Buffer.alloc(0);
|
|
227
|
+
|
|
228
|
+
client.on('data', (chunk) => {
|
|
229
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
230
|
+
const headerEnd = buffered.indexOf('\r\n\r\n');
|
|
231
|
+
if (headerEnd === -1) {
|
|
232
|
+
if (buffered.length > 65536) {
|
|
233
|
+
client.removeAllListeners('data');
|
|
234
|
+
client.pause();
|
|
235
|
+
denyProxyRequest(client, '431 Request Header Fields Too Large');
|
|
236
|
+
}
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
client.pause();
|
|
241
|
+
client.removeAllListeners('data');
|
|
242
|
+
|
|
243
|
+
const header = buffered.subarray(0, headerEnd).toString('utf-8');
|
|
244
|
+
const rest = buffered.subarray(headerEnd + 4);
|
|
245
|
+
if (authorization) {
|
|
246
|
+
const supplied = header
|
|
247
|
+
.split(/\r?\n/)
|
|
248
|
+
.find((line) => line.toLowerCase().startsWith('proxy-authorization:'))
|
|
249
|
+
?.slice('proxy-authorization:'.length)
|
|
250
|
+
.trim();
|
|
251
|
+
if (supplied !== authorization) {
|
|
252
|
+
denyProxyRequest(client, '407 Proxy Authentication Required');
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const [method, target] = header.split(/\r?\n/, 1)[0].split(' ');
|
|
257
|
+
|
|
258
|
+
const task =
|
|
259
|
+
method?.toUpperCase() === 'CONNECT' && target
|
|
260
|
+
? handleConnect(client, target, rest)
|
|
261
|
+
: handleHttp(client, header, rest);
|
|
262
|
+
task.catch(() => denyProxyRequest(client, '502 Bad Gateway'));
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const server = createServer(handleClient);
|
|
267
|
+
let stopped = false;
|
|
268
|
+
|
|
269
|
+
return new Promise((resolve, reject) => {
|
|
270
|
+
const listen = (port) => {
|
|
271
|
+
server.once('error', (error) => {
|
|
272
|
+
if (error.code === 'EADDRINUSE' && portRange && port < portRange.high) {
|
|
273
|
+
listen(port + 1);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
reject(error);
|
|
277
|
+
});
|
|
278
|
+
server.listen(port, '127.0.0.1', () => {
|
|
279
|
+
server.removeAllListeners('error');
|
|
280
|
+
const address = server.address();
|
|
281
|
+
|
|
282
|
+
resolve({
|
|
283
|
+
port: address.port,
|
|
284
|
+
stop: () =>
|
|
285
|
+
new Promise((done) => {
|
|
286
|
+
if (stopped) {
|
|
287
|
+
done();
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
stopped = true;
|
|
291
|
+
for (const socket of sockets) socket.destroy();
|
|
292
|
+
server.close(() => done());
|
|
293
|
+
}),
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
};
|
|
297
|
+
listen(portRange ? portRange.low : 0);
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
module.exports = {
|
|
302
|
+
isPublicProxyAddress,
|
|
303
|
+
startFilterProxy,
|
|
304
|
+
};
|
package/lib/shared.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
LandstripControlResponse,
|
|
5
|
+
LandstripFilesystemTrap,
|
|
6
|
+
LandstripNetworkTrap,
|
|
7
|
+
LandstripTrap,
|
|
8
|
+
} from './index.js';
|
|
9
|
+
|
|
10
|
+
export type LandstripDenialTrap = LandstripFilesystemTrap | LandstripNetworkTrap;
|
|
11
|
+
|
|
12
|
+
export function isRecord(value: unknown): value is Record<string, unknown>;
|
|
13
|
+
|
|
14
|
+
export function expandHomePath(path: string): string;
|
|
15
|
+
|
|
16
|
+
export function expandPath(filePath: string, baseDirectory: string): string;
|
|
17
|
+
|
|
18
|
+
export function canonicalizePath(filePath: string, baseDirectory: string): string;
|
|
19
|
+
|
|
20
|
+
export function canonicalizeGlobPattern(pattern: string, baseDirectory: string): string;
|
|
21
|
+
|
|
22
|
+
export function normalizePathSeparators(path: string): string;
|
|
23
|
+
|
|
24
|
+
export function globToRegExp(globPattern: string): RegExp;
|
|
25
|
+
|
|
26
|
+
export function pathUnderDirectory(filePath: string, dir: string): boolean;
|
|
27
|
+
|
|
28
|
+
export function sessionAllows(prefixes: Set<string>, filePath: string): boolean;
|
|
29
|
+
|
|
30
|
+
export function sessionScopeFor(filePath: string, baseDirectory: string): string;
|
|
31
|
+
|
|
32
|
+
export function domainMatchesPattern(domain: string, pattern: string): boolean;
|
|
33
|
+
|
|
34
|
+
export function domainMatchesAny(domain: string, patterns: string[]): boolean;
|
|
35
|
+
|
|
36
|
+
export function allowsAllDomains(allowedDomains: string[]): boolean;
|
|
37
|
+
|
|
38
|
+
export function decodeLandstripTrap(value: unknown): LandstripTrap | null;
|
|
39
|
+
|
|
40
|
+
export function parseTrapLine(line: string): LandstripTrap | null;
|
|
41
|
+
|
|
42
|
+
export function parseLandstripTraps(output: string): LandstripTrap[];
|
|
43
|
+
|
|
44
|
+
export function isFilesystemTrap(trap: LandstripTrap): trap is LandstripFilesystemTrap;
|
|
45
|
+
|
|
46
|
+
export function isDenialTrap(trap: LandstripTrap): trap is LandstripDenialTrap;
|
|
47
|
+
|
|
48
|
+
export function isQueryTrap(trap: LandstripTrap): trap is LandstripDenialTrap;
|
|
49
|
+
|
|
50
|
+
export function formatLandstripTrap(trap: LandstripTrap): string;
|
|
51
|
+
|
|
52
|
+
export function formatLandstripTraps(traps: LandstripTrap[]): string;
|
|
53
|
+
|
|
54
|
+
export function controlResponseLine(
|
|
55
|
+
queryId: string,
|
|
56
|
+
action: LandstripControlResponse['action'],
|
|
57
|
+
): string;
|
package/lib/shared.js
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { lstatSync, readlinkSync, realpathSync } = require('node:fs');
|
|
5
|
+
const { homedir } = require('node:os');
|
|
6
|
+
const { basename, dirname, isAbsolute, join, relative, resolve, sep } = require('node:path');
|
|
7
|
+
|
|
8
|
+
function isRecord(value) {
|
|
9
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function expandHomePath(value) {
|
|
13
|
+
if (value === '~' || value === '$HOME') return homedir();
|
|
14
|
+
if (value.startsWith('~/')) return join(homedir(), value.slice(2));
|
|
15
|
+
if (value.startsWith('$HOME/')) return join(homedir(), value.slice(6));
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function pathUnderDirectory(filePath, dir) {
|
|
20
|
+
const child = relative(dir, filePath);
|
|
21
|
+
return child === '' || (!isAbsolute(child) && child !== '..' && !child.startsWith(`..${sep}`));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sessionAllows(prefixes, filePath) {
|
|
25
|
+
for (const prefix of prefixes) {
|
|
26
|
+
if (pathUnderDirectory(filePath, prefix)) return true;
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The broadest ancestor worth approving in one action: the immediate child of
|
|
32
|
+
// `$HOME` (e.g. `~/.cargo`) for paths under the user's home, the project root
|
|
33
|
+
// for paths under it, otherwise the containing directory. A file sitting
|
|
34
|
+
// directly on a boundary falls back to the exact file so nothing widens
|
|
35
|
+
// silently.
|
|
36
|
+
function sessionScopeFor(filePath, baseDirectory) {
|
|
37
|
+
const dir = dirname(filePath);
|
|
38
|
+
const homeBoundaries = new Set([homedir()]);
|
|
39
|
+
try {
|
|
40
|
+
homeBoundaries.add(realpathSync.native(homedir()));
|
|
41
|
+
} catch {
|
|
42
|
+
// $HOME not resolvable — fall back to the raw value only.
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (const boundary of homeBoundaries) {
|
|
46
|
+
if (pathUnderDirectory(dir, boundary)) {
|
|
47
|
+
const first = relative(boundary, dir).split(sep)[0];
|
|
48
|
+
if (!first) return filePath;
|
|
49
|
+
return join(boundary, first);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const projectBoundaries = new Set([baseDirectory]);
|
|
54
|
+
try {
|
|
55
|
+
projectBoundaries.add(realpathSync.native(baseDirectory));
|
|
56
|
+
} catch {
|
|
57
|
+
// Project directory not resolvable — fall back to the raw value only.
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
for (const boundary of projectBoundaries) {
|
|
61
|
+
if (pathUnderDirectory(dir, boundary)) return boundary;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return dir;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function domainMatchesPattern(domain, pattern) {
|
|
68
|
+
// A trailing dot ("pastebin.com.") is the same host to DNS but would slip
|
|
69
|
+
// past a literal deny entry; strip it from both sides before matching.
|
|
70
|
+
const normalizedDomain = domain.toLowerCase().replace(/\.+$/, '');
|
|
71
|
+
const normalizedPattern = pattern.toLowerCase().replace(/\.+$/, '');
|
|
72
|
+
|
|
73
|
+
if (normalizedPattern === '*') return true;
|
|
74
|
+
if (normalizedPattern.startsWith('*.')) {
|
|
75
|
+
const base = normalizedPattern.slice(2);
|
|
76
|
+
return normalizedDomain === base || normalizedDomain.endsWith(`.${base}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return normalizedDomain === normalizedPattern;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function domainMatchesAny(domain, patterns) {
|
|
83
|
+
return patterns.some((pattern) => domainMatchesPattern(domain, pattern));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function allowsAllDomains(allowedDomains) {
|
|
87
|
+
return allowedDomains.includes('*');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// landstrip emits each trap as a flat JSON record tagged by a `kind`
|
|
91
|
+
// discriminant (`filesystem`, `network`, `launch`, `usage`, `internal`)
|
|
92
|
+
// alongside a stable `code` and variant-specific fields. The declarations it
|
|
93
|
+
// ships are erased at compile time, so validate the fields callers read
|
|
94
|
+
// before trusting a decoded line. `state` is deliberately not validated: a
|
|
95
|
+
// missing or unknown state degrades to "informational", the safe direction.
|
|
96
|
+
// `query_id` must be a string — landstrip < 0.17 sent a number, and a
|
|
97
|
+
// numeric id fails its own deserializer when echoed back.
|
|
98
|
+
const LANDSTRIP_OPERATIONS = new Set(['read', 'write']);
|
|
99
|
+
|
|
100
|
+
function isLandstripTrap(value) {
|
|
101
|
+
if (!isRecord(value)) return false;
|
|
102
|
+
|
|
103
|
+
switch (value.kind) {
|
|
104
|
+
case 'filesystem':
|
|
105
|
+
return (
|
|
106
|
+
LANDSTRIP_OPERATIONS.has(value.operation) &&
|
|
107
|
+
typeof value.path === 'string' &&
|
|
108
|
+
typeof value.query_id === 'string'
|
|
109
|
+
);
|
|
110
|
+
case 'network':
|
|
111
|
+
return (
|
|
112
|
+
typeof value.operation === 'string' &&
|
|
113
|
+
typeof value.target === 'string' &&
|
|
114
|
+
typeof value.query_id === 'string'
|
|
115
|
+
);
|
|
116
|
+
case 'launch':
|
|
117
|
+
return typeof value.program === 'string' && typeof value.message === 'string';
|
|
118
|
+
case 'usage':
|
|
119
|
+
return typeof value.message === 'string';
|
|
120
|
+
case 'internal':
|
|
121
|
+
return typeof value.code === 'string' && typeof value.message === 'string';
|
|
122
|
+
default:
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function decodeLandstripTrap(value) {
|
|
128
|
+
return isLandstripTrap(value) ? value : null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function parseTrapLine(line) {
|
|
132
|
+
try {
|
|
133
|
+
const parsed = JSON.parse(line);
|
|
134
|
+
return isLandstripTrap(parsed) ? parsed : null;
|
|
135
|
+
} catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function parseLandstripTraps(output) {
|
|
141
|
+
const traps = [];
|
|
142
|
+
|
|
143
|
+
for (const line of output.split('\n')) {
|
|
144
|
+
const trimmed = line.trim();
|
|
145
|
+
if (trimmed.length === 0 || trimmed[0] !== '{') continue;
|
|
146
|
+
const trap = parseTrapLine(trimmed);
|
|
147
|
+
if (trap) traps.push(trap);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return traps;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function isFilesystemTrap(trap) {
|
|
154
|
+
return trap.kind === 'filesystem';
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// filesystem and network traps report an access the policy denied; launch,
|
|
158
|
+
// usage and internal traps report that landstrip itself failed.
|
|
159
|
+
function isDenialTrap(trap) {
|
|
160
|
+
return trap.kind === 'filesystem' || trap.kind === 'network';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// A `state: "query"` trap suspends the child's syscall until the host answers
|
|
164
|
+
// it on the trap socket. An `info` trap is terminal.
|
|
165
|
+
function isQueryTrap(trap) {
|
|
166
|
+
return isDenialTrap(trap) && trap.state === 'query';
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function formatLandstripTrap(trap) {
|
|
170
|
+
switch (trap.kind) {
|
|
171
|
+
case 'filesystem':
|
|
172
|
+
return `landstrip: filesystem ${trap.operation} denied (${trap.path})${
|
|
173
|
+
trap.mechanism ? ` [${trap.mechanism}]` : ''
|
|
174
|
+
}`;
|
|
175
|
+
case 'network':
|
|
176
|
+
return `landstrip: network ${trap.operation} denied (${trap.target})${
|
|
177
|
+
trap.mechanism ? ` [${trap.mechanism}]` : ''
|
|
178
|
+
}`;
|
|
179
|
+
case 'launch':
|
|
180
|
+
return `landstrip: launch failed (${trap.program})${trap.message ? `: ${trap.message}` : ''}`;
|
|
181
|
+
case 'usage':
|
|
182
|
+
return `landstrip: usage error: ${trap.message}`;
|
|
183
|
+
case 'internal': {
|
|
184
|
+
const mechanism = trap.mechanism ? ` [${trap.mechanism}]` : '';
|
|
185
|
+
return `landstrip: ${trap.code}${mechanism}: ${trap.message}`;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function formatLandstripTraps(traps) {
|
|
191
|
+
return traps.map(formatLandstripTrap).join('\n');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Relative entries (notably ".") resolve against the caller-supplied base
|
|
195
|
+
// directory — the command's working directory that landstrip itself uses as
|
|
196
|
+
// its policy base — never the host process's own cwd.
|
|
197
|
+
function expandPath(filePath, baseDirectory) {
|
|
198
|
+
return resolve(baseDirectory, expandHomePath(filePath));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function canonicalizePath(filePath, baseDirectory, seen = new Set()) {
|
|
202
|
+
const abs = expandPath(filePath, baseDirectory);
|
|
203
|
+
const missing = [];
|
|
204
|
+
let existing = abs;
|
|
205
|
+
|
|
206
|
+
for (;;) {
|
|
207
|
+
try {
|
|
208
|
+
const stat = lstatSync(existing);
|
|
209
|
+
if (stat.isSymbolicLink()) {
|
|
210
|
+
if (seen.has(existing)) return abs;
|
|
211
|
+
seen.add(existing);
|
|
212
|
+
const target = resolve(dirname(existing), readlinkSync(existing), ...missing);
|
|
213
|
+
return canonicalizePath(target, baseDirectory, seen);
|
|
214
|
+
}
|
|
215
|
+
break;
|
|
216
|
+
} catch {
|
|
217
|
+
const parent = dirname(existing);
|
|
218
|
+
if (parent === existing) return abs;
|
|
219
|
+
missing.unshift(basename(existing));
|
|
220
|
+
existing = parent;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
try {
|
|
225
|
+
return resolve(realpathSync.native(existing), ...missing);
|
|
226
|
+
} catch {
|
|
227
|
+
return abs;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function canonicalizeGlobPattern(pattern, baseDirectory) {
|
|
232
|
+
const expanded = expandPath(pattern, baseDirectory);
|
|
233
|
+
const wildcard = expanded.indexOf('*');
|
|
234
|
+
if (wildcard < 0) return canonicalizePath(expanded, baseDirectory);
|
|
235
|
+
|
|
236
|
+
const prefix = expanded.slice(0, wildcard);
|
|
237
|
+
const base = prefix.endsWith(sep) ? prefix : dirname(prefix);
|
|
238
|
+
const suffixOffset = base.endsWith(sep) ? base.length - 1 : base.length;
|
|
239
|
+
const canonicalBase = canonicalizePath(base, baseDirectory);
|
|
240
|
+
const suffix = expanded.slice(suffixOffset);
|
|
241
|
+
return canonicalBase.endsWith(sep) && suffix.startsWith(sep)
|
|
242
|
+
? `${canonicalBase}${suffix.slice(1)}`
|
|
243
|
+
: `${canonicalBase}${suffix}`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function normalizePathSeparators(path) {
|
|
247
|
+
return process.platform === 'win32' ? path.replaceAll('\\', '/') : path;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const globRegExpCache = new Map();
|
|
251
|
+
|
|
252
|
+
// Translates an absolute glob pattern to a regular expression using standard
|
|
253
|
+
// path semantics: `**` crosses directory boundaries (and `**/` may match zero
|
|
254
|
+
// segments), while a single `*` is confined to one path segment.
|
|
255
|
+
function globToRegExp(globPattern) {
|
|
256
|
+
const cached = globRegExpCache.get(globPattern);
|
|
257
|
+
if (cached) return cached;
|
|
258
|
+
|
|
259
|
+
const escaped = globPattern
|
|
260
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
261
|
+
.replace(/\*\*\/|\*\*|\*/g, (token) =>
|
|
262
|
+
token === '**/' ? '(?:.*/)?' : token === '**' ? '.*' : '[^/]*',
|
|
263
|
+
);
|
|
264
|
+
const result = new RegExp(`^${escaped}$`);
|
|
265
|
+
globRegExpCache.set(globPattern, result);
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// The broker matches an answer to its query by the exact decimal `query_id`
|
|
270
|
+
// string the trap carried. A numeric id fails its deserializer, the line is
|
|
271
|
+
// dropped, and the child's syscall stays suspended.
|
|
272
|
+
function controlResponseLine(queryId, action) {
|
|
273
|
+
return JSON.stringify({ query_id: queryId, action }) + '\n';
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
module.exports = {
|
|
277
|
+
isRecord,
|
|
278
|
+
expandHomePath,
|
|
279
|
+
expandPath,
|
|
280
|
+
canonicalizePath,
|
|
281
|
+
canonicalizeGlobPattern,
|
|
282
|
+
normalizePathSeparators,
|
|
283
|
+
globToRegExp,
|
|
284
|
+
pathUnderDirectory,
|
|
285
|
+
sessionAllows,
|
|
286
|
+
sessionScopeFor,
|
|
287
|
+
domainMatchesPattern,
|
|
288
|
+
domainMatchesAny,
|
|
289
|
+
allowsAllDomains,
|
|
290
|
+
decodeLandstripTrap,
|
|
291
|
+
parseTrapLine,
|
|
292
|
+
parseLandstripTraps,
|
|
293
|
+
isFilesystemTrap,
|
|
294
|
+
isDenialTrap,
|
|
295
|
+
isQueryTrap,
|
|
296
|
+
formatLandstripTrap,
|
|
297
|
+
formatLandstripTraps,
|
|
298
|
+
controlResponseLine,
|
|
299
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@landstrip/landstrip-api",
|
|
3
|
+
"version": "0.18.39",
|
|
4
|
+
"description": "Sandbox runner using Landlock, Seatbelt, and AppContainer",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://github.com/landstrip/landstrip#readme",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/landstrip/landstrip.git"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/landstrip/landstrip/issues"
|
|
13
|
+
},
|
|
14
|
+
"main": "lib/index.js",
|
|
15
|
+
"types": "lib/index.d.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./lib/index.d.ts",
|
|
19
|
+
"default": "./lib/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./shared": {
|
|
22
|
+
"types": "./lib/shared.d.ts",
|
|
23
|
+
"default": "./lib/shared.js"
|
|
24
|
+
},
|
|
25
|
+
"./proxy": {
|
|
26
|
+
"types": "./lib/proxy.d.ts",
|
|
27
|
+
"default": "./lib/proxy.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"bin": {
|
|
31
|
+
"landstrip": "bin/landstrip.js"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin",
|
|
35
|
+
"lib",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"optionalDependencies": {
|
|
40
|
+
"@landstrip/landstrip-darwin-arm64": "0.18.39",
|
|
41
|
+
"@landstrip/landstrip-darwin-x64": "0.18.39",
|
|
42
|
+
"@landstrip/landstrip-linux-x64": "0.18.39",
|
|
43
|
+
"@landstrip/landstrip-linux-arm64": "0.18.39",
|
|
44
|
+
"@landstrip/landstrip-win32-x64": "0.18.39",
|
|
45
|
+
"@landstrip/landstrip-win32-arm64": "0.18.39"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=18"
|
|
52
|
+
}
|
|
53
|
+
}
|