@benchcutlogic/edge-kit 0.0.0-stage → 0.2.1
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 +172 -2
- package/dist/analytics.d.ts +41 -0
- package/dist/analytics.js +212 -0
- package/dist/body.d.ts +55 -0
- package/dist/body.js +177 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/scrub.d.ts +128 -0
- package/dist/scrub.js +636 -0
- package/dist/ssrf.d.ts +165 -0
- package/dist/ssrf.js +643 -0
- package/dist/sveltekit.d.ts +60 -0
- package/dist/sveltekit.js +149 -0
- package/dist/tenant.d.ts +44 -0
- package/dist/tenant.js +43 -0
- package/package.json +87 -3
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
CHANGED
|
@@ -1,3 +1,173 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @benchcutlogic/edge-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Security helpers for code that runs at the edge of a web app: outbound fetches with SSRF protection, request and response body reads with a byte cap, secret scrubbing for error reports, analytics that drop private URL parts, a SvelteKit security `handle`, and tenant scoping for database queries.
|
|
4
|
+
|
|
5
|
+
Most functions return [Effect](https://effect.website) values. Run them with `Effect.runPromise` or compose them into your own Effect programs.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @benchcutlogic/edge-kit effect
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`effect` is a peer dependency (`^4.0.7`), so your app and this package share one copy.
|
|
14
|
+
|
|
15
|
+
## Requirements
|
|
16
|
+
|
|
17
|
+
- Node.js 20 or later, or a runtime with the Fetch API and `ReadableStream` (Cloudflare Workers, Deno, Bun).
|
|
18
|
+
- ESM. The package ships ES modules only. Node versions that support `require()` of ES modules can also load it from CommonJS.
|
|
19
|
+
- TypeScript users: `moduleResolution` set to `nodenext`, `node16`, or `bundler`, so the subpath exports resolve.
|
|
20
|
+
- `ssrfFetch` connects through `node:http` and `node:https` and resolves names with `node:dns`. In a runtime without those modules, pass your own `dnsResolve` and `fetch` (see below).
|
|
21
|
+
|
|
22
|
+
## Subpath exports
|
|
23
|
+
|
|
24
|
+
Each module has its own entry point. The package root re-exports all of them.
|
|
25
|
+
|
|
26
|
+
| Import | Contents |
|
|
27
|
+
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
28
|
+
| `'@benchcutlogic/edge-kit/ssrf'` | `ssrfFetch`, `assertPublicHttpUrl`, `isPrivateOrReservedIp`, `createNodeDnsResolver`, `createPinnedNodeFetch` |
|
|
29
|
+
| `'@benchcutlogic/edge-kit/body'` | `readCappedBytes`, `readCappedText`, `readCappedJson` |
|
|
30
|
+
| `'@benchcutlogic/edge-kit/scrub'` | `scrubString`, `scrubObject`, `scrubError`, `templatePath`, `createSentryBeforeSend`, `assertScrubberInvariants` |
|
|
31
|
+
| `'@benchcutlogic/edge-kit/analytics'` | `createSafeAnalytics`, `sanitizeAnalyticsUrl` |
|
|
32
|
+
| `'@benchcutlogic/edge-kit/sveltekit'` | `createEdgeSecurityHandle`, `applySecurityHeaders` |
|
|
33
|
+
| `'@benchcutlogic/edge-kit/tenant'` | `TenantId`, `ActorAuth`, `CurrentTenant`, `createScopedQueryRunner` |
|
|
34
|
+
| `'@benchcutlogic/edge-kit'` | Everything above |
|
|
35
|
+
|
|
36
|
+
### `ssrf`
|
|
37
|
+
|
|
38
|
+
`ssrfFetch` only connects to public addresses. It rejects non-HTTPS URLs (unless `allowHttp` is set), URLs with credentials, `localhost` and `*.local`/`*.internal` names, and any host whose DNS answer includes a private or reserved IP. It connects to the address it validated, checks every redirect the same way, drops `Authorization` and `Cookie` on cross-origin redirects, and caps both total time and body size.
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import * as Effect from 'effect/Effect';
|
|
42
|
+
import { ssrfFetch } from '@benchcutlogic/edge-kit/ssrf';
|
|
43
|
+
|
|
44
|
+
const response = await Effect.runPromise(
|
|
45
|
+
ssrfFetch('https://example.com/feed.json', {
|
|
46
|
+
totalTimeoutMs: 5_000,
|
|
47
|
+
maxResponseBytes: 256 * 1024,
|
|
48
|
+
maxRedirects: 2
|
|
49
|
+
})
|
|
50
|
+
);
|
|
51
|
+
console.log(response.status, response.json());
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`totalTimeoutMs` is required. `maxResponseBytes` defaults to 5 MiB and `maxRedirects` to 3. Failures are typed: `InvalidUrlError`, `SsrfBlockedError`, `DeadlineExceededError`, `NetworkError`, `BodyTooLargeError`, and `BodyReadError`.
|
|
55
|
+
|
|
56
|
+
To validate a URL without fetching it:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import * as Effect from 'effect/Effect';
|
|
60
|
+
import { assertPublicHttpUrl } from '@benchcutlogic/edge-kit/ssrf';
|
|
61
|
+
|
|
62
|
+
const url = await Effect.runPromise(
|
|
63
|
+
assertPublicHttpUrl(userSuppliedUrl, { allowedHosts: ['*.example.com'] })
|
|
64
|
+
);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Without `node:dns` and `node:http`, `ssrfFetch` fails closed for host names. Pass a `dnsResolve` function that returns the host's IP addresses, and a `fetch` transport that connects to `init.resolvedAddresses` rather than resolving the name again.
|
|
68
|
+
|
|
69
|
+
### `body`
|
|
70
|
+
|
|
71
|
+
Reads a `Response` or `ReadableStream<Uint8Array>` and stops as soon as the byte limit is passed. When the source is a `Response` whose `Content-Length` is over the limit, it fails before reading. For an incoming `Request`, pass `request.body`.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import * as Effect from 'effect/Effect';
|
|
75
|
+
import * as Schema from 'effect/Schema';
|
|
76
|
+
import { readCappedJson } from '@benchcutlogic/edge-kit/body';
|
|
77
|
+
|
|
78
|
+
const Signup = Schema.Struct({ email: Schema.String });
|
|
79
|
+
|
|
80
|
+
export async function POST({ request }: { request: Request }) {
|
|
81
|
+
const body = await Effect.runPromise(
|
|
82
|
+
readCappedJson(request.body, Signup, { maxBytes: 16 * 1024 })
|
|
83
|
+
);
|
|
84
|
+
return new Response(`hello ${body.email}`);
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The error channel is `BodyTooLargeError | BodyReadError | InvalidJsonError | Schema.SchemaError`. `readCappedText` and `readCappedBytes` take a source and a byte limit.
|
|
89
|
+
|
|
90
|
+
### `scrub`
|
|
91
|
+
|
|
92
|
+
Removes Bearer and Basic credentials, secret query parameters, secret header lines, and raw JSON from `SyntaxError` messages. Key names such as `password`, `token`, `api_key`, and `cookie` are redacted in objects. Add your own with `secretKeys`.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import * as Sentry from '@sentry/node';
|
|
96
|
+
import { assertScrubberInvariants, createSentryBeforeSend } from '@benchcutlogic/edge-kit/scrub';
|
|
97
|
+
|
|
98
|
+
const beforeSend = createSentryBeforeSend({ secretKeys: ['x-session-id'] });
|
|
99
|
+
assertScrubberInvariants(beforeSend); // throws if a known secret pattern gets through
|
|
100
|
+
|
|
101
|
+
Sentry.init({ dsn: process.env.SENTRY_DSN, beforeSend });
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The hook is generic over the event type, so it can be assigned to `beforeSend` without a cast and returns the event type that Sentry passes in. `assertScrubberInvariants` also accepts a hook you write yourself with Sentry's `(event: ErrorEvent, hint: EventHint)` signature.
|
|
105
|
+
|
|
106
|
+
`scrubString`, `scrubObject`, and `scrubError` work without Sentry:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { scrubError, templatePath } from '@benchcutlogic/edge-kit/scrub';
|
|
110
|
+
|
|
111
|
+
logger.error(scrubError(err));
|
|
112
|
+
templatePath('https://example.com/users/42?token=abc'); // 'https://example.com/users/:id'
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### `analytics`
|
|
116
|
+
|
|
117
|
+
Wraps `gtag` (or any transport you pass) so page views and events never carry query strings, fragments, or IDs in the path, and nothing is sent from excluded routes. The default excluded prefixes are `/admin`, `/app`, and `/auth`. Passing `excludedPrefixes` replaces them.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { createSafeAnalytics } from '@benchcutlogic/edge-kit/analytics';
|
|
121
|
+
|
|
122
|
+
const analytics = createSafeAnalytics({ excludedPrefixes: ['/account', '/billing'] });
|
|
123
|
+
|
|
124
|
+
analytics.pageView('https://example.com/docs/42?utm_source=x');
|
|
125
|
+
// sends page_view with page_location 'https://example.com/docs/:id'
|
|
126
|
+
|
|
127
|
+
analytics.event('signup_click', { plan: 'pro' });
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Call `analytics.setCurrentPath(url)` after client-side navigation so events are attributed to the new page and suppressed on excluded routes.
|
|
131
|
+
|
|
132
|
+
### `sveltekit`
|
|
133
|
+
|
|
134
|
+
`createEdgeSecurityHandle` returns a SvelteKit `handle`. It sets security headers on every response, including errors and redirects, answers disallowed methods with `405` and an `Allow` header, and rejects state-changing requests whose `Origin` does not match.
|
|
135
|
+
|
|
136
|
+
The returned value is assignable to SvelteKit's `Handle` type under `strict`. The example is for SvelteKit 2, which exports `Handle` from `@sveltejs/kit`. SvelteKit 3 exports it from `@sveltejs/kit/hooks`, so change only that import.
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
// src/hooks.server.ts
|
|
140
|
+
import type { Handle } from '@sveltejs/kit';
|
|
141
|
+
import { createEdgeSecurityHandle } from '@benchcutlogic/edge-kit/sveltekit';
|
|
142
|
+
|
|
143
|
+
export const handle: Handle = createEdgeSecurityHandle({
|
|
144
|
+
methodRules: [{ pattern: '/api/webhooks/*', methods: ['POST'] }],
|
|
145
|
+
csrfExemptPaths: ['/api/webhooks/*'],
|
|
146
|
+
headers: { contentSecurityPolicy: false } // when SvelteKit's kit.csp sets the policy
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The defaults are HSTS for two years with `preload`, `Referrer-Policy: strict-origin-when-cross-origin`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, and a restrictive CSP when the response has none. Set a header to `false` to omit it or to a string to replace it. `applySecurityHeaders(response, config)` applies the same headers outside SvelteKit.
|
|
151
|
+
|
|
152
|
+
### `tenant`
|
|
153
|
+
|
|
154
|
+
`createScopedQueryRunner` wraps a database handle so every query needs the `CurrentTenant` service. A query cannot run until the request's tenant has been provided.
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import * as Effect from 'effect/Effect';
|
|
158
|
+
import * as Schema from 'effect/Schema';
|
|
159
|
+
import { ActorAuth, CurrentTenant, createScopedQueryRunner } from '@benchcutlogic/edge-kit/tenant';
|
|
160
|
+
|
|
161
|
+
const scoped = createScopedQueryRunner(db);
|
|
162
|
+
|
|
163
|
+
const listProjects = scoped.run(({ db, tenantId }) =>
|
|
164
|
+
Effect.promise(() => db.query('select * from projects where tenant_id = ?', [tenantId]))
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
const actor = Schema.decodeUnknownSync(ActorAuth)({ actorId: 'user_1', tenantId: 'tenant_1' });
|
|
168
|
+
const rows = await Effect.runPromise(Effect.provideService(listProjects, CurrentTenant, actor));
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## License
|
|
172
|
+
|
|
173
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export declare const DEFAULT_EXCLUDED_PREFIXES: ReadonlyArray<string>;
|
|
2
|
+
export type AnalyticsTransport = (command: 'event' | 'config' | 'js' | 'set', target: string, params?: Record<string, unknown>) => void;
|
|
3
|
+
export interface SanitizeAnalyticsUrlOptions {
|
|
4
|
+
readonly excludedPrefixes?: ReadonlyArray<string>;
|
|
5
|
+
readonly redactPath?: (pathname: string) => string;
|
|
6
|
+
readonly isReferrer?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface SafeAnalyticsOptions {
|
|
9
|
+
readonly excludedPrefixes?: ReadonlyArray<string>;
|
|
10
|
+
readonly redactPath?: (pathname: string) => string;
|
|
11
|
+
readonly transport?: AnalyticsTransport;
|
|
12
|
+
readonly getCurrentLocation?: () => string | undefined;
|
|
13
|
+
readonly getReferrer?: () => string | undefined;
|
|
14
|
+
}
|
|
15
|
+
export interface PageViewOptions {
|
|
16
|
+
readonly referrer?: string;
|
|
17
|
+
readonly title?: string;
|
|
18
|
+
readonly params?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
export interface SafeAnalytics {
|
|
21
|
+
isExcludedPath(pathOrUrl: string): boolean;
|
|
22
|
+
setCurrentPath(pathOrUrl: string): void;
|
|
23
|
+
pageView(location?: string, options?: PageViewOptions): boolean;
|
|
24
|
+
event(name: string, params?: Record<string, unknown>, location?: string): boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Sanitizes an analytics URL (`page_location` or `page_referrer`) by:
|
|
28
|
+
* - stripping query strings, hash fragments, and embedded userinfo
|
|
29
|
+
* - collapsing private dynamic segments (UUIDs, numeric IDs, tokens, emails)
|
|
30
|
+
* and applying an optional custom `redactPath`
|
|
31
|
+
* - omitting the URL (`undefined`) when `isReferrer` is true and the referrer
|
|
32
|
+
* path matches any `excludedPrefixes`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function sanitizeAnalyticsUrl(rawUrl: string, options?: SanitizeAnalyticsUrlOptions): string | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a privacy-safe analytics emitter that strips query strings, hashes,
|
|
37
|
+
* and dynamic path segments from both `page_location` and `page_referrer`, and
|
|
38
|
+
* suspends all `pageView` and `event` emission on excluded routes (including
|
|
39
|
+
* across SPA navigation transitions).
|
|
40
|
+
*/
|
|
41
|
+
export declare function createSafeAnalytics(options?: SafeAnalyticsOptions): SafeAnalytics;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { templatePath } from './scrub.js';
|
|
2
|
+
export const DEFAULT_EXCLUDED_PREFIXES = ['/admin', '/app', '/auth'];
|
|
3
|
+
function normalizePrefix(prefix) {
|
|
4
|
+
const trimmed = prefix.trim().toLowerCase();
|
|
5
|
+
if (trimmed === '' || trimmed === '/')
|
|
6
|
+
return '/';
|
|
7
|
+
const withLeading = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
8
|
+
return withLeading.replace(/\/+$/, '');
|
|
9
|
+
}
|
|
10
|
+
function extractPathname(pathOrUrl) {
|
|
11
|
+
const trimmed = pathOrUrl.trim();
|
|
12
|
+
if (trimmed.length === 0)
|
|
13
|
+
return '/';
|
|
14
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
15
|
+
try {
|
|
16
|
+
return new URL(trimmed).pathname;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return trimmed.split(/[?#]/, 1)[0] ?? '/';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const withoutQuery = trimmed.split(/[?#]/, 1)[0] ?? '/';
|
|
23
|
+
return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}`;
|
|
24
|
+
}
|
|
25
|
+
function matchesExcludedPrefix(pathname, prefixes) {
|
|
26
|
+
const normalizedPath = pathname.toLowerCase();
|
|
27
|
+
for (const rawPrefix of prefixes) {
|
|
28
|
+
const prefix = normalizePrefix(rawPrefix);
|
|
29
|
+
if (prefix === '/')
|
|
30
|
+
return true;
|
|
31
|
+
if (normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`)) {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Sanitizes an analytics URL (`page_location` or `page_referrer`) by:
|
|
39
|
+
* - stripping query strings, hash fragments, and embedded userinfo
|
|
40
|
+
* - collapsing private dynamic segments (UUIDs, numeric IDs, tokens, emails)
|
|
41
|
+
* and applying an optional custom `redactPath`
|
|
42
|
+
* - omitting the URL (`undefined`) when `isReferrer` is true and the referrer
|
|
43
|
+
* path matches any `excludedPrefixes`.
|
|
44
|
+
*/
|
|
45
|
+
export function sanitizeAnalyticsUrl(rawUrl, options) {
|
|
46
|
+
const trimmed = rawUrl.trim();
|
|
47
|
+
if (trimmed.length === 0)
|
|
48
|
+
return undefined;
|
|
49
|
+
const excludedPrefixes = options?.excludedPrefixes ?? DEFAULT_EXCLUDED_PREFIXES;
|
|
50
|
+
let origin = '';
|
|
51
|
+
let pathname = '';
|
|
52
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = new URL(trimmed);
|
|
55
|
+
origin = parsed.origin;
|
|
56
|
+
pathname = parsed.pathname;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
pathname = extractPathname(trimmed);
|
|
64
|
+
}
|
|
65
|
+
if (options?.isReferrer === true && matchesExcludedPrefix(pathname, excludedPrefixes)) {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
const redactedPath = options?.redactPath ? options.redactPath(pathname) : templatePath(pathname);
|
|
69
|
+
const cleanPath = redactedPath.split(/[?#]/, 1)[0] ?? redactedPath;
|
|
70
|
+
const normalizedPath = cleanPath.startsWith('/') ? cleanPath : `/${cleanPath}`;
|
|
71
|
+
return origin ? `${origin}${normalizedPath}` : normalizedPath;
|
|
72
|
+
}
|
|
73
|
+
function resolveDefaultTransport() {
|
|
74
|
+
const globalRecord = globalThis;
|
|
75
|
+
return typeof globalRecord.gtag === 'function'
|
|
76
|
+
? globalRecord.gtag
|
|
77
|
+
: undefined;
|
|
78
|
+
}
|
|
79
|
+
function resolveDefaultLocation() {
|
|
80
|
+
const globalRecord = globalThis;
|
|
81
|
+
return typeof globalRecord.location?.href === 'string' ? globalRecord.location.href : undefined;
|
|
82
|
+
}
|
|
83
|
+
function resolveDefaultReferrer() {
|
|
84
|
+
const globalRecord = globalThis;
|
|
85
|
+
return typeof globalRecord.document?.referrer === 'string'
|
|
86
|
+
? globalRecord.document.referrer
|
|
87
|
+
: undefined;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Creates a privacy-safe analytics emitter that strips query strings, hashes,
|
|
91
|
+
* and dynamic path segments from both `page_location` and `page_referrer`, and
|
|
92
|
+
* suspends all `pageView` and `event` emission on excluded routes (including
|
|
93
|
+
* across SPA navigation transitions).
|
|
94
|
+
*/
|
|
95
|
+
export function createSafeAnalytics(options) {
|
|
96
|
+
const excludedPrefixes = options?.excludedPrefixes ?? DEFAULT_EXCLUDED_PREFIXES;
|
|
97
|
+
const redactPath = options?.redactPath;
|
|
98
|
+
let trackedLocation = undefined;
|
|
99
|
+
function getTransport() {
|
|
100
|
+
return options?.transport ?? resolveDefaultTransport();
|
|
101
|
+
}
|
|
102
|
+
function resolveCurrentLocation(explicit) {
|
|
103
|
+
if (explicit !== undefined)
|
|
104
|
+
return explicit;
|
|
105
|
+
if (trackedLocation !== undefined)
|
|
106
|
+
return trackedLocation;
|
|
107
|
+
return options?.getCurrentLocation ? options.getCurrentLocation() : resolveDefaultLocation();
|
|
108
|
+
}
|
|
109
|
+
function isExcludedPath(pathOrUrl) {
|
|
110
|
+
return matchesExcludedPrefix(extractPathname(pathOrUrl), excludedPrefixes);
|
|
111
|
+
}
|
|
112
|
+
function setCurrentPath(pathOrUrl) {
|
|
113
|
+
trackedLocation = pathOrUrl;
|
|
114
|
+
}
|
|
115
|
+
function pageView(location, pageOptions) {
|
|
116
|
+
if (location !== undefined) {
|
|
117
|
+
trackedLocation = location;
|
|
118
|
+
}
|
|
119
|
+
const currentLocation = resolveCurrentLocation(location);
|
|
120
|
+
if (currentLocation === undefined || isExcludedPath(currentLocation)) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
const transport = getTransport();
|
|
124
|
+
if (!transport)
|
|
125
|
+
return false;
|
|
126
|
+
const sanitizedLocation = sanitizeAnalyticsUrl(currentLocation, {
|
|
127
|
+
excludedPrefixes,
|
|
128
|
+
redactPath,
|
|
129
|
+
isReferrer: false
|
|
130
|
+
});
|
|
131
|
+
if (sanitizedLocation === undefined)
|
|
132
|
+
return false;
|
|
133
|
+
const rawReferrer = pageOptions?.referrer ??
|
|
134
|
+
(options?.getReferrer ? options.getReferrer() : resolveDefaultReferrer());
|
|
135
|
+
const sanitizedReferrer = rawReferrer !== undefined
|
|
136
|
+
? sanitizeAnalyticsUrl(rawReferrer, {
|
|
137
|
+
excludedPrefixes,
|
|
138
|
+
redactPath,
|
|
139
|
+
isReferrer: true
|
|
140
|
+
})
|
|
141
|
+
: undefined;
|
|
142
|
+
const payload = {
|
|
143
|
+
...(pageOptions?.params ?? {}),
|
|
144
|
+
page_location: sanitizedLocation
|
|
145
|
+
};
|
|
146
|
+
if (sanitizedReferrer !== undefined) {
|
|
147
|
+
payload.page_referrer = sanitizedReferrer;
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
delete payload.page_referrer;
|
|
151
|
+
}
|
|
152
|
+
if (pageOptions?.title !== undefined) {
|
|
153
|
+
payload.page_title = pageOptions.title;
|
|
154
|
+
}
|
|
155
|
+
transport('event', 'page_view', payload);
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
function event(name, params, location) {
|
|
159
|
+
const currentLocation = resolveCurrentLocation(location);
|
|
160
|
+
if (currentLocation !== undefined && isExcludedPath(currentLocation)) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
const transport = getTransport();
|
|
164
|
+
if (!transport)
|
|
165
|
+
return false;
|
|
166
|
+
const payload = { ...(params ?? {}) };
|
|
167
|
+
if (typeof payload.page_location === 'string') {
|
|
168
|
+
const cleanLoc = sanitizeAnalyticsUrl(payload.page_location, {
|
|
169
|
+
excludedPrefixes,
|
|
170
|
+
redactPath,
|
|
171
|
+
isReferrer: false
|
|
172
|
+
});
|
|
173
|
+
if (cleanLoc !== undefined) {
|
|
174
|
+
payload.page_location = cleanLoc;
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
delete payload.page_location;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else if (currentLocation !== undefined) {
|
|
181
|
+
const cleanLoc = sanitizeAnalyticsUrl(currentLocation, {
|
|
182
|
+
excludedPrefixes,
|
|
183
|
+
redactPath,
|
|
184
|
+
isReferrer: false
|
|
185
|
+
});
|
|
186
|
+
if (cleanLoc !== undefined) {
|
|
187
|
+
payload.page_location = cleanLoc;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (typeof payload.page_referrer === 'string') {
|
|
191
|
+
const cleanRef = sanitizeAnalyticsUrl(payload.page_referrer, {
|
|
192
|
+
excludedPrefixes,
|
|
193
|
+
redactPath,
|
|
194
|
+
isReferrer: true
|
|
195
|
+
});
|
|
196
|
+
if (cleanRef !== undefined) {
|
|
197
|
+
payload.page_referrer = cleanRef;
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
delete payload.page_referrer;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
transport('event', name, payload);
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
isExcludedPath,
|
|
208
|
+
setCurrentPath,
|
|
209
|
+
pageView,
|
|
210
|
+
event
|
|
211
|
+
};
|
|
212
|
+
}
|