@stealthmark/core 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +141 -2
- package/dist/auto-discovery.d.ts +22 -0
- package/dist/auto-discovery.d.ts.map +1 -0
- package/dist/auto-discovery.js +93 -0
- package/dist/auto-discovery.js.map +1 -0
- package/dist/create.d.ts +51 -0
- package/dist/create.d.ts.map +1 -0
- package/dist/create.js +94 -0
- package/dist/create.js.map +1 -0
- package/dist/detect-agent.d.ts +18 -0
- package/dist/detect-agent.d.ts.map +1 -0
- package/dist/detect-agent.js +106 -0
- package/dist/detect-agent.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest.d.ts +12 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +36 -0
- package/dist/manifest.js.map +1 -0
- package/dist/request-context.d.ts +33 -0
- package/dist/request-context.d.ts.map +1 -0
- package/dist/request-context.js +86 -0
- package/dist/request-context.js.map +1 -0
- package/dist/types.d.ts +150 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/usage-reporter.d.ts +28 -0
- package/dist/usage-reporter.d.ts.map +1 -0
- package/dist/usage-reporter.js +272 -0
- package/dist/usage-reporter.js.map +1 -0
- package/package.json +57 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,142 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @stealthmark/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Framework-agnostic engine for detecting self-identified AI agents, serving an agent manifest and metering agent traffic.**
|
|
4
|
+
|
|
5
|
+
> Detects only agents that identify themselves. It does not detect stealth bots and is not a security control.
|
|
6
|
+
|
|
7
|
+
Detect AI agents that identify themselves, serve a structured agent manifest, and meter that traffic. Plain TypeScript, no runtime dependencies. It does not detect agents that disguise themselves, and it is not a security control.
|
|
8
|
+
|
|
9
|
+
The manifest is StealthMark's own format. It is not an A2A Agent Card, an MCP server manifest or an adopted standard.
|
|
10
|
+
|
|
11
|
+
> **Status:** v0.1.0, not published to npm yet. The `npm install` and `npx` commands below will work once it is published; until then build from source as described in the [repository README](https://github.com/Gastonchevarria/stealthmark-sdk#status).
|
|
12
|
+
|
|
13
|
+
## Installation from source
|
|
14
|
+
|
|
15
|
+
Until the first npm release, build the repository and install the tarball:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# in a clone of the repository
|
|
19
|
+
npm install && npm run build
|
|
20
|
+
npm pack -w @stealthmark/core
|
|
21
|
+
# in your project
|
|
22
|
+
npm install /path/to/stealthmark-core-0.1.0.tgz
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Installation (after the first npm release)
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install @stealthmark/core
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Requires Node.js 20 or newer.
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { createStealthMark } from '@stealthmark/core';
|
|
37
|
+
|
|
38
|
+
const sm = createStealthMark({
|
|
39
|
+
siteName: 'My SaaS',
|
|
40
|
+
capabilities: [
|
|
41
|
+
{ id: 'search', endpoint: '/api/search', method: 'GET', description: 'Search products' },
|
|
42
|
+
{ id: 'create-order', endpoint: '/api/orders', method: 'POST', hitl: true },
|
|
43
|
+
],
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// In your request handler:
|
|
47
|
+
const result = sm.detect(request.headers);
|
|
48
|
+
|
|
49
|
+
if (result.isAgent) {
|
|
50
|
+
return new Response(sm.manifestJson, {
|
|
51
|
+
headers: { 'content-type': 'application/agent+json' },
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`hitl` is advisory metadata for agents. StealthMark does not block, approve or rate-limit anything; enforce approvals in your own handler. The same goes for `pricing`: it is published in the manifest and never enforced.
|
|
57
|
+
|
|
58
|
+
## Agent Detection
|
|
59
|
+
|
|
60
|
+
StealthMark detects agents that identify themselves, via three signals (priority order):
|
|
61
|
+
|
|
62
|
+
1. **Accept header**: `application/agent+json`
|
|
63
|
+
2. **StealthMark header**: `x-stealthmark-agent`
|
|
64
|
+
3. **User-Agent patterns**: GPTBot, ClaudeBot, PerplexityBot, etc.
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
import { detectAgent } from '@stealthmark/core';
|
|
68
|
+
|
|
69
|
+
const result = detectAgent(request.headers);
|
|
70
|
+
// { isAgent: true, agentId: 'GPTBot', method: 'user-agent' }
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
All three signals are self-declared. Any client can send them, and agents that look like browsers are not detected.
|
|
74
|
+
|
|
75
|
+
## Usage Metering
|
|
76
|
+
|
|
77
|
+
Usage is counted per **agent event**: one HTTP request that identifies itself as an AI agent (via `Accept: application/agent+json`, the `x-stealthmark-agent` header, or a known agent token in the `User-Agent`). Identification is self-declared, so a human or script can send these signals and be counted, and agents that look like browsers are not counted. Events are reported best-effort and can be dropped (see below). They are batched and sent to `POST /v1/usage/ingest` with your site API key.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
const sm = createStealthMark({
|
|
81
|
+
siteName: 'My App',
|
|
82
|
+
apiKey: process.env.STEALTHMARK_API_KEY,
|
|
83
|
+
// usageEndpoint: 'https://...', // or STEALTHMARK_USAGE_ENDPOINT
|
|
84
|
+
// reportUsage: false, // opt out (defaults to true when a key is set)
|
|
85
|
+
siteId: process.env.STEALTHMARK_SITE_ID, // optional, stored as site_id (UUID of a registered site)
|
|
86
|
+
onQuotaExceeded: ({ pausedUntil, retryAfterSeconds, dropped }) => {
|
|
87
|
+
// Optional: surface the pause (log, alert, status page). Never throws into the SDK.
|
|
88
|
+
logger.warn(`StealthMark quota reached, reporting paused until ${new Date(pausedUntil).toISOString()}`);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
sm.recordAgentEvent({
|
|
93
|
+
event_type: 'agent_request', // 'agent_request' | 'agent_blocked' | 'agent_manifest'
|
|
94
|
+
agent_identifier: 'GPTBot',
|
|
95
|
+
metadata: { path: '/pricing', method: 'GET' },
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
sm.usage.stats(); // { queued, sent, dropped, failures, pausedUntil, quotaExceededUntil }
|
|
99
|
+
await sm.usage.flush(); // e.g. before a serverless function or process exits
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The `@stealthmark/next` and `@stealthmark/express` adapters call `recordAgentEvent` exactly once per agent request for you.
|
|
103
|
+
|
|
104
|
+
**Site attribution.** The adapters add `metadata.host` to every metered event (the `Host` header, lowercased, no port). The console groups and filters by `metadata.host`, automatically and with no config. Set `trustForwardedHost: true` to read the first `X-Forwarded-Host` value instead; enable it only behind a proxy you control.
|
|
105
|
+
|
|
106
|
+
`siteId` (or the `STEALTHMARK_SITE_ID` env var) is optional and only stored on the event as `site_id`. It must be the UUID of a site registered to the same organization, otherwise it is stored as null; a value that is not a UUID is ignored with one warning. `normalizeHost`, `resolveRequestHost` and `buildEventMetadata` are exported if you meter events yourself.
|
|
107
|
+
|
|
108
|
+
Behavior:
|
|
109
|
+
|
|
110
|
+
- Never throws, never blocks the request path, no dependencies (global `fetch`); timers are unref'd so the reporter never keeps a process alive.
|
|
111
|
+
- Batches by `maxBatch` (default 100, max 500) or `flushIntervalMs` (default 1000).
|
|
112
|
+
- Retries 5xx and network errors three times (250 ms, 1 s, 4 s), then drops the batch (`failures`, `dropped`).
|
|
113
|
+
- On `429 quota_exceeded` it stops sending for `retry_after_seconds` (default 300) and drops events meanwhile (`stats().dropped`), exposing the resume time as `stats().pausedUntil` (`null` when not paused; `quotaExceededUntil` is the same value kept for compatibility). Pass `onQuotaExceeded` to be told when it happens: it receives `{ pausedUntil, retryAfterSeconds, dropped }` once per 429, and exceptions it throws are swallowed. Events are not buffered across the pause, so a customer who wants to alert on it should wire this callback. Your site keeps serving traffic; only reporting pauses.
|
|
114
|
+
- Any other `429` is the API's per-key rate limiter (`rate_limit_exceeded`), not a quota problem: nothing is dropped, `pausedUntil` stays `null` and `onQuotaExceeded` is not called. The batch stays queued and sending resumes after the `Retry-After` header (or `retry_after` in the body; 60 seconds when neither is present, never more than 300). Events recorded during the wait are queued, up to 10,000, and `flush()` returns without sending until the wait is over.
|
|
115
|
+
- On serverless or Edge runtimes, pending timers can be frozen after the response is sent. Call `await sm.usage.flush()` (or `event.waitUntil(sm.usage.flush())`) at the end of the request when you need delivery guarantees.
|
|
116
|
+
|
|
117
|
+
You can also use the reporter standalone:
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
import { createUsageReporter } from '@stealthmark/core';
|
|
121
|
+
|
|
122
|
+
const usage = createUsageReporter({ apiKey: process.env.STEALTHMARK_API_KEY ?? '', maxBatch: 50 });
|
|
123
|
+
usage.record({ event_type: 'agent_request' });
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Data sent to StealthMark Cloud
|
|
127
|
+
|
|
128
|
+
Only when an API key is configured (`apiKey` option or `STEALTHMARK_API_KEY`). Without a key the SDK makes no network calls. Requests not identified as agents are never reported.
|
|
129
|
+
|
|
130
|
+
- Usage events (`POST /v1/usage/ingest`, sent with `Authorization: Bearer $STEALTHMARK_API_KEY`): event type, agent identifier, request path, method, host and timestamp. When no better identifier exists, the agent identifier is the request's `User-Agent`. Set `reportUsage: false` to turn this off.
|
|
131
|
+
|
|
132
|
+
The default host is https://stealthmark-api-cifepjj5ca-uc.a.run.app, the StealthMark hosted API. Override it with `usageEndpoint` or `STEALTHMARK_USAGE_ENDPOINT`.
|
|
133
|
+
|
|
134
|
+
## Route discovery
|
|
135
|
+
|
|
136
|
+
`discoverCapabilities()` lists Next.js App Router `route.ts` handlers under `app/api` or `src/app/api` as capabilities. It does not scan Express, Fastify or Pages Router routes; declare those in `capabilities`. It never sets `pricing`, and sets `hitl` only for paths matching the `hitlKeywords` you pass.
|
|
137
|
+
|
|
138
|
+
`discoverCapabilities()` needs Node (`fs`). Do not call it from Edge or browser code.
|
|
139
|
+
|
|
140
|
+
## License
|
|
141
|
+
|
|
142
|
+
Apache 2.0, see [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Capability } from './types.js';
|
|
2
|
+
export interface RouteDiscoveryOptions {
|
|
3
|
+
/** Root directory to scan from (defaults to process.cwd()) */
|
|
4
|
+
rootDir?: string;
|
|
5
|
+
/** Directories to scan (defaults to `src/app/api` and `app/api` under `rootDir`) */
|
|
6
|
+
apiPaths?: string[];
|
|
7
|
+
/**
|
|
8
|
+
* Opt-in: routes whose path contains one of these keywords are published with `hitl: true`.
|
|
9
|
+
* Empty by default, so discovery never guesses which routes need human approval.
|
|
10
|
+
*/
|
|
11
|
+
hitlKeywords?: string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Lists Next.js App Router route handlers (`route.ts`, `route.js`, `route.mts`, `route.mjs`) found under
|
|
15
|
+
* `app/api` or `src/app/api` as capabilities. A handler is listed once per HTTP method it exports.
|
|
16
|
+
* Routes whose exported methods cannot be determined are skipped.
|
|
17
|
+
*
|
|
18
|
+
* It does not scan Express, Fastify or Pages Router routes, and it assumes nothing about pricing or
|
|
19
|
+
* human approval. Needs Node (`fs`): do not call it from Edge or browser code.
|
|
20
|
+
*/
|
|
21
|
+
export declare function discoverCapabilities(options?: RouteDiscoveryOptions): Capability[];
|
|
22
|
+
//# sourceMappingURL=auto-discovery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto-discovery.d.ts","sourceRoot":"","sources":["../src/auto-discovery.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,YAAY,CAAC;AAIzD,MAAM,WAAW,qBAAqB;IACpC,8DAA8D;IAC9D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oFAAoF;IACpF,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AA8BD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,qBAA0B,GAAG,UAAU,EAAE,CAkBtF"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
2
|
+
// @stealthmark/core — Route Discovery (Node only)
|
|
3
|
+
// Lists Next.js App Router route handlers as manifest capabilities
|
|
4
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
5
|
+
import * as fs from 'fs';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
8
|
+
const METHOD_FUNCTION_EXPORT = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\b/g;
|
|
9
|
+
const METHOD_CONST_EXPORT = /\bexport\s+(?:const|let|var)\s+(GET|POST|PUT|PATCH|DELETE)\b/g;
|
|
10
|
+
const EXPORT_LIST = /\bexport\s*\{([^}]*)\}/g;
|
|
11
|
+
function detectExportedMethods(source) {
|
|
12
|
+
const methods = new Set();
|
|
13
|
+
for (const pattern of [METHOD_FUNCTION_EXPORT, METHOD_CONST_EXPORT]) {
|
|
14
|
+
for (const match of source.matchAll(pattern)) {
|
|
15
|
+
methods.add(match[1]);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
for (const list of source.matchAll(EXPORT_LIST)) {
|
|
19
|
+
for (const specifier of list[1].split(',')) {
|
|
20
|
+
const parts = specifier.trim().split(/\s+as\s+/);
|
|
21
|
+
const exportedName = parts[parts.length - 1]?.trim();
|
|
22
|
+
if (exportedName && HTTP_METHODS.includes(exportedName)) {
|
|
23
|
+
methods.add(exportedName);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return methods;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Lists Next.js App Router route handlers (`route.ts`, `route.js`, `route.mts`, `route.mjs`) found under
|
|
31
|
+
* `app/api` or `src/app/api` as capabilities. A handler is listed once per HTTP method it exports.
|
|
32
|
+
* Routes whose exported methods cannot be determined are skipped.
|
|
33
|
+
*
|
|
34
|
+
* It does not scan Express, Fastify or Pages Router routes, and it assumes nothing about pricing or
|
|
35
|
+
* human approval. Needs Node (`fs`): do not call it from Edge or browser code.
|
|
36
|
+
*/
|
|
37
|
+
export function discoverCapabilities(options = {}) {
|
|
38
|
+
const rootDir = options.rootDir || (typeof process !== 'undefined' && process.cwd ? process.cwd() : '.');
|
|
39
|
+
const hitlKeywords = (options.hitlKeywords ?? []).map((kw) => kw.toLowerCase());
|
|
40
|
+
const capabilities = [];
|
|
41
|
+
const candidateDirs = options.apiPaths || [
|
|
42
|
+
path.join(rootDir, 'src', 'app', 'api'),
|
|
43
|
+
path.join(rootDir, 'app', 'api'),
|
|
44
|
+
];
|
|
45
|
+
for (const dir of candidateDirs) {
|
|
46
|
+
if (fs.existsSync(dir)) {
|
|
47
|
+
scanAppApiDirectory(dir, dir, capabilities, hitlKeywords);
|
|
48
|
+
break; // Only scan the first matching API root directory to prevent duplicate routes
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return capabilities;
|
|
52
|
+
}
|
|
53
|
+
function scanAppApiDirectory(currentDir, apiRootDir, out, hitlKeywords) {
|
|
54
|
+
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
const fullPath = path.join(currentDir, entry.name);
|
|
57
|
+
if (entry.isDirectory()) {
|
|
58
|
+
scanAppApiDirectory(fullPath, apiRootDir, out, hitlKeywords);
|
|
59
|
+
}
|
|
60
|
+
else if (entry.isFile() &&
|
|
61
|
+
(entry.name === 'route.ts' ||
|
|
62
|
+
entry.name === 'route.js' ||
|
|
63
|
+
entry.name === 'route.mts' ||
|
|
64
|
+
entry.name === 'route.mjs')) {
|
|
65
|
+
// Derive endpoint path relative to api root
|
|
66
|
+
const relDir = path.relative(apiRootDir, currentDir);
|
|
67
|
+
const endpoint = '/api' + (relDir ? '/' + relDir.replace(/\\/g, '/') : '');
|
|
68
|
+
try {
|
|
69
|
+
const content = fs.readFileSync(fullPath, 'utf8');
|
|
70
|
+
const detectedMethods = detectExportedMethods(content);
|
|
71
|
+
for (const method of detectedMethods) {
|
|
72
|
+
const slug = endpoint
|
|
73
|
+
.replace(/^\/api\/?/, '')
|
|
74
|
+
.replace(/\//g, '-')
|
|
75
|
+
.replace(/\[([^\]]+)\]/g, '$1') || 'root';
|
|
76
|
+
const id = `${slug}-${method.toLowerCase()}`;
|
|
77
|
+
const isHitl = hitlKeywords.some((kw) => endpoint.toLowerCase().includes(kw));
|
|
78
|
+
out.push({
|
|
79
|
+
id,
|
|
80
|
+
endpoint,
|
|
81
|
+
method,
|
|
82
|
+
description: `API endpoint for ${endpoint} (${method})`,
|
|
83
|
+
...(isHitl ? { hitl: true } : {}),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Silently skip unreadable files
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
//# sourceM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Y,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;oBAE9E,GAAG,CAAC,IAAI,CAAC;wBACP,EAAE;wBACF,QAAQ;wBACR,MAAM;wBACN,WAAW,EAAE,oBAAoB,QAAQ,KAAK,MAAM,GAAG;wBACvD,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBAClC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,iCAAiC;YACnC,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC"}
|
package/dist/create.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { StealthMarkConfig, AgentManifest, DetectionResult, UsageEvent, AgentPolicy } from './types.js';
|
|
2
|
+
import { type UsageReporter } from './usage-reporter.js';
|
|
3
|
+
/** The StealthMark runtime instance returned by createStealthMark() */
|
|
4
|
+
export interface StealthMarkInstance {
|
|
5
|
+
/** The generated agent manifest */
|
|
6
|
+
readonly manifest: AgentManifest;
|
|
7
|
+
/** Serialized manifest JSON string */
|
|
8
|
+
readonly manifestJson: string;
|
|
9
|
+
/** Detect whether a request is from an agent */
|
|
10
|
+
detect: (headers: Headers | Record<string, string | undefined>) => DetectionResult;
|
|
11
|
+
/** Standard response headers to add */
|
|
12
|
+
readonly responseHeaders: Record<string, string>;
|
|
13
|
+
/** Best-effort usage reporter (inert when no API key is configured) */
|
|
14
|
+
readonly usage: UsageReporter;
|
|
15
|
+
/** Effective handling of agent requests on ordinary paths */
|
|
16
|
+
readonly agentPolicy: AgentPolicy;
|
|
17
|
+
/** Registered site id attached to every metered event (config `siteId`, else STEALTHMARK_SITE_ID); undefined when not set or not a UUID */
|
|
18
|
+
readonly siteId: string | undefined;
|
|
19
|
+
/** Whether the adapters read the request host from X-Forwarded-Host instead of Host (config `trustForwardedHost`, default false) */
|
|
20
|
+
readonly trustForwardedHost: boolean;
|
|
21
|
+
/** Meter one agent event. Call exactly once per request identified as an AI agent. */
|
|
22
|
+
recordAgentEvent: (event: UsageEvent) => void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Creates a configured StealthMark instance.
|
|
26
|
+
*
|
|
27
|
+
* This is the main entry point for the SDK. It initializes agent detection,
|
|
28
|
+
* manifest generation and usage metering.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* import { createStealthMark } from '@stealthmark/core';
|
|
33
|
+
*
|
|
34
|
+
* const sm = createStealthMark({
|
|
35
|
+
* siteName: 'My SaaS',
|
|
36
|
+
* capabilities: [
|
|
37
|
+
* { id: 'search', endpoint: '/api/search', method: 'GET' },
|
|
38
|
+
* ],
|
|
39
|
+
* });
|
|
40
|
+
*
|
|
41
|
+
* // In your request handler:
|
|
42
|
+
* const result = sm.detect(request.headers);
|
|
43
|
+
* if (result.isAgent) {
|
|
44
|
+
* return new Response(sm.manifestJson, {
|
|
45
|
+
* headers: { 'content-type': 'application/agent+json' },
|
|
46
|
+
* });
|
|
47
|
+
* }
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function createStealthMark(config: StealthMarkConfig): StealthMarkInstance;
|
|
51
|
+
//# sourceMappingURL=create.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,iBAAiB,EACjB,aAAa,EACb,eAAe,EACf,UAAU,EACV,WAAW,EACZ,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAuB,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE9E,uEAAuE;AACvE,MAAM,WAAW,mBAAmB;IAClC,mCAAmC;IACnC,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC;IACjC,sCAAsC;IACtC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,gDAAgD;IAChD,MAAM,EAAE,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,KAAK,eAAe,CAAC;IACnF,uCAAuC;IACvC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjD,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,6DAA6D;IAC7D,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC,2IAA2I;IAC3I,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,oIAAoI;IACpI,QAAQ,CAAC,kBAAkB,EAAE,OAAO,CAAC;IACrC,sFAAsF;IACtF,gBAAgB,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;CAC/C;AAgCD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,GAAG,mBAAmB,CAqChF"}
|
package/dist/create.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
2
|
+
// @stealthmark/core — Factory & Orchestrator
|
|
3
|
+
// Creates a configured StealthMark instance that handles requests
|
|
4
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
5
|
+
import { detectAgent } from './detect-agent.js';
|
|
6
|
+
import { generateManifest, serializeManifest } from './manifest.js';
|
|
7
|
+
import { createUsageReporter } from './usage-reporter.js';
|
|
8
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
9
|
+
function readEnv(name) {
|
|
10
|
+
if (typeof process === 'undefined' || !process.env)
|
|
11
|
+
return undefined;
|
|
12
|
+
switch (name) {
|
|
13
|
+
case 'STEALTHMARK_API_KEY':
|
|
14
|
+
return process.env.STEALTHMARK_API_KEY || undefined;
|
|
15
|
+
case 'STEALTHMARK_USAGE_ENDPOINT':
|
|
16
|
+
return process.env.STEALTHMARK_USAGE_ENDPOINT || undefined;
|
|
17
|
+
case 'STEALTHMARK_SITE_ID':
|
|
18
|
+
return process.env.STEALTHMARK_SITE_ID || undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The ingest API rejects the whole batch when one event carries a site_id that is not a UUID, so a
|
|
23
|
+
* malformed id is dropped (with one warning) instead of costing the site its metered events.
|
|
24
|
+
*/
|
|
25
|
+
function resolveSiteId(configured) {
|
|
26
|
+
const raw = configured?.trim() || readEnv('STEALTHMARK_SITE_ID')?.trim();
|
|
27
|
+
if (!raw)
|
|
28
|
+
return undefined;
|
|
29
|
+
if (UUID_PATTERN.test(raw))
|
|
30
|
+
return raw.toLowerCase();
|
|
31
|
+
if (typeof console !== 'undefined') {
|
|
32
|
+
console.warn('[stealthmark] siteId ignored: expected the UUID of a site registered in the StealthMark console.');
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Creates a configured StealthMark instance.
|
|
38
|
+
*
|
|
39
|
+
* This is the main entry point for the SDK. It initializes agent detection,
|
|
40
|
+
* manifest generation and usage metering.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* import { createStealthMark } from '@stealthmark/core';
|
|
45
|
+
*
|
|
46
|
+
* const sm = createStealthMark({
|
|
47
|
+
* siteName: 'My SaaS',
|
|
48
|
+
* capabilities: [
|
|
49
|
+
* { id: 'search', endpoint: '/api/search', method: 'GET' },
|
|
50
|
+
* ],
|
|
51
|
+
* });
|
|
52
|
+
*
|
|
53
|
+
* // In your request handler:
|
|
54
|
+
* const result = sm.detect(request.headers);
|
|
55
|
+
* if (result.isAgent) {
|
|
56
|
+
* return new Response(sm.manifestJson, {
|
|
57
|
+
* headers: { 'content-type': 'application/agent+json' },
|
|
58
|
+
* });
|
|
59
|
+
* }
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
export function createStealthMark(config) {
|
|
63
|
+
const manifest = generateManifest(config);
|
|
64
|
+
const manifestJson = serializeManifest(manifest);
|
|
65
|
+
const usageApiKey = config.apiKey ?? readEnv('STEALTHMARK_API_KEY');
|
|
66
|
+
const siteId = resolveSiteId(config.siteId);
|
|
67
|
+
const trustForwardedHost = config.trustForwardedHost === true;
|
|
68
|
+
const usage = createUsageReporter({
|
|
69
|
+
apiKey: config.reportUsage === false ? '' : (usageApiKey ?? ''),
|
|
70
|
+
endpoint: config.usageEndpoint ?? readEnv('STEALTHMARK_USAGE_ENDPOINT'),
|
|
71
|
+
onQuotaExceeded: config.onQuotaExceeded,
|
|
72
|
+
});
|
|
73
|
+
const responseHeaders = {
|
|
74
|
+
'x-stealthmark-shield': 'ACTIVE',
|
|
75
|
+
'x-stealthmark-agent-policy': config.agentPolicy ?? 'observe',
|
|
76
|
+
...(config.headers ?? {}),
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
manifest,
|
|
80
|
+
manifestJson,
|
|
81
|
+
agentPolicy: config.agentPolicy ?? 'observe',
|
|
82
|
+
siteId,
|
|
83
|
+
trustForwardedHost,
|
|
84
|
+
detect(headers) {
|
|
85
|
+
return detectAgent(headers, config.agentPatterns);
|
|
86
|
+
},
|
|
87
|
+
responseHeaders,
|
|
88
|
+
usage,
|
|
89
|
+
recordAgentEvent(event) {
|
|
90
|
+
usage.record(siteId && !event.site_id ? { ...event, site_id: siteId } : event);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=create.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,6C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