@hazeljs/guardrails 0.2.0-beta.50
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 +192 -0
- package/README.md +158 -0
- package/dist/checks/injection.check.d.ts +12 -0
- package/dist/checks/injection.check.d.ts.map +1 -0
- package/dist/checks/injection.check.js +36 -0
- package/dist/checks/pii.check.d.ts +10 -0
- package/dist/checks/pii.check.d.ts.map +1 -0
- package/dist/checks/pii.check.js +41 -0
- package/dist/checks/toxicity.check.d.ts +13 -0
- package/dist/checks/toxicity.check.d.ts.map +1 -0
- package/dist/checks/toxicity.check.js +31 -0
- package/dist/decorators/guardrail-input.decorator.d.ts +8 -0
- package/dist/decorators/guardrail-input.decorator.d.ts.map +1 -0
- package/dist/decorators/guardrail-input.decorator.js +37 -0
- package/dist/decorators/guardrail-output.decorator.d.ts +8 -0
- package/dist/decorators/guardrail-output.decorator.d.ts.map +1 -0
- package/dist/decorators/guardrail-output.decorator.js +34 -0
- package/dist/errors/guardrail-violation.error.d.ts +14 -0
- package/dist/errors/guardrail-violation.error.d.ts.map +1 -0
- package/dist/errors/guardrail-violation.error.js +23 -0
- package/dist/guardrails.module.d.ts +12 -0
- package/dist/guardrails.module.d.ts.map +1 -0
- package/dist/guardrails.module.js +48 -0
- package/dist/guardrails.service.d.ts +29 -0
- package/dist/guardrails.service.d.ts.map +1 -0
- package/dist/guardrails.service.js +207 -0
- package/dist/guardrails.types.d.ts +29 -0
- package/dist/guardrails.types.d.ts.map +1 -0
- package/dist/guardrails.types.js +5 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +23 -0
- package/dist/interceptors/guardrail.interceptor.d.ts +18 -0
- package/dist/interceptors/guardrail.interceptor.d.ts.map +1 -0
- package/dist/interceptors/guardrail.interceptor.js +47 -0
- package/dist/pipes/guardrail.pipe.d.ts +14 -0
- package/dist/pipes/guardrail.pipe.d.ts.map +1 -0
- package/dist/pipes/guardrail.pipe.js +38 -0
- package/package.json +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2024 HazelJS Team
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
22
|
+
|
|
23
|
+
1. Definitions.
|
|
24
|
+
|
|
25
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
26
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
27
|
+
|
|
28
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
29
|
+
the copyright owner that is granting the License.
|
|
30
|
+
|
|
31
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
32
|
+
other entities that control, are controlled by, or are under common
|
|
33
|
+
control with that entity. For the purposes of this definition,
|
|
34
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
35
|
+
direction or management of such entity, whether by contract or
|
|
36
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
37
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
38
|
+
|
|
39
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
40
|
+
exercising permissions granted by this License.
|
|
41
|
+
|
|
42
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
43
|
+
including but not limited to software source code, documentation
|
|
44
|
+
source, and configuration files.
|
|
45
|
+
|
|
46
|
+
"Object" form shall mean any form resulting from mechanical
|
|
47
|
+
transformation or translation of a Source form, including but
|
|
48
|
+
not limited to compiled object code, generated documentation,
|
|
49
|
+
and conversions to other media types.
|
|
50
|
+
|
|
51
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
52
|
+
Object form, made available under the License, as indicated by a
|
|
53
|
+
copyright notice that is included in or attached to the work
|
|
54
|
+
(an example is provided in the Appendix below).
|
|
55
|
+
|
|
56
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
57
|
+
form, that is based on (or derived from) the Work and for which the
|
|
58
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
59
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
60
|
+
of this License, Derivative Works shall not include works that remain
|
|
61
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
62
|
+
the Work and Derivative Works thereof.
|
|
63
|
+
|
|
64
|
+
"Contribution" shall mean any work of authorship, including
|
|
65
|
+
the original version of the Work and any modifications or additions
|
|
66
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
67
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
68
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
69
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
70
|
+
means any form of electronic, verbal, or written communication sent
|
|
71
|
+
to the Licensor or its representatives, including but not limited to
|
|
72
|
+
communication on electronic mailing lists, source code control systems,
|
|
73
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
74
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
75
|
+
excluding communication that is conspicuously marked or otherwise
|
|
76
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
77
|
+
|
|
78
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
79
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
80
|
+
subsequently incorporated within the Work.
|
|
81
|
+
|
|
82
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
83
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
84
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
85
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
86
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
87
|
+
Work and such Derivative Works in Source or Object form.
|
|
88
|
+
|
|
89
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
90
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
91
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
92
|
+
(except as stated in this section) patent license to make, have made,
|
|
93
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
94
|
+
where such license applies only to those patent claims licensable
|
|
95
|
+
by such Contributor that are necessarily infringed by their
|
|
96
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
97
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
98
|
+
institute patent litigation against any entity (including a
|
|
99
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
100
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
101
|
+
or contributory patent infringement, then any patent licenses
|
|
102
|
+
granted to You under this License for that Work shall terminate
|
|
103
|
+
as of the date such litigation is filed.
|
|
104
|
+
|
|
105
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
106
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
107
|
+
modifications, and in Source or Object form, provided that You
|
|
108
|
+
meet the following conditions:
|
|
109
|
+
|
|
110
|
+
(a) You must give any other recipients of the Work or
|
|
111
|
+
Derivative Works a copy of this License; and
|
|
112
|
+
|
|
113
|
+
(b) You must cause any modified files to carry prominent notices
|
|
114
|
+
stating that You changed the files; and
|
|
115
|
+
|
|
116
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
117
|
+
that You distribute, all copyright, patent, trademark, and
|
|
118
|
+
attribution notices from the Source form of the Work,
|
|
119
|
+
excluding those notices that do not pertain to any part of
|
|
120
|
+
the Derivative Works; and
|
|
121
|
+
|
|
122
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
123
|
+
distribution, then any Derivative Works that You distribute must
|
|
124
|
+
include a readable copy of the attribution notices contained
|
|
125
|
+
within such NOTICE file, excluding those notices that do not
|
|
126
|
+
pertain to any part of the Derivative Works, in at least one
|
|
127
|
+
of the following places: within a NOTICE text file distributed
|
|
128
|
+
as part of the Derivative Works; within the Source form or
|
|
129
|
+
documentation, if provided along with the Derivative Works; or,
|
|
130
|
+
within a display generated by the Derivative Works, if and
|
|
131
|
+
wherever such third-party notices normally appear. The contents
|
|
132
|
+
of the NOTICE file are for informational purposes only and
|
|
133
|
+
do not modify the License. You may add Your own attribution
|
|
134
|
+
notices within Derivative Works that You distribute, alongside
|
|
135
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
136
|
+
that such additional attribution notices cannot be construed
|
|
137
|
+
as modifying the License.
|
|
138
|
+
|
|
139
|
+
You may add Your own copyright statement to Your modifications and
|
|
140
|
+
may provide additional or different license terms and conditions
|
|
141
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
142
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
143
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
144
|
+
the conditions stated in this License.
|
|
145
|
+
|
|
146
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
147
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
148
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
149
|
+
this License, without any additional terms or conditions.
|
|
150
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
151
|
+
the terms of any separate license agreement you may have executed
|
|
152
|
+
with Licensor regarding such Contributions.
|
|
153
|
+
|
|
154
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
155
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
156
|
+
except as required for reasonable and customary use in describing the
|
|
157
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
158
|
+
|
|
159
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
160
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
161
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
162
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
163
|
+
implied, including, without limitation, any warranties or conditions
|
|
164
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
165
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
166
|
+
appropriateness of using or redistributing the Work and assume any
|
|
167
|
+
risks associated with Your exercise of permissions under this License.
|
|
168
|
+
|
|
169
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
170
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
171
|
+
unless required by applicable law (such as deliberate and grossly
|
|
172
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
173
|
+
liable to You for damages, including any direct, indirect, special,
|
|
174
|
+
incidental, or consequential damages of any character arising as a
|
|
175
|
+
result of this License or out of the use or inability to use the
|
|
176
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
177
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
178
|
+
other commercial damages or losses), even if such Contributor
|
|
179
|
+
has been advised of the possibility of such damages.
|
|
180
|
+
|
|
181
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
182
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
183
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
184
|
+
or other liability obligations and/or rights consistent with this
|
|
185
|
+
License. However, in accepting such obligations, You may act only
|
|
186
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
187
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
188
|
+
defend, and hold each Contributor harmless for any liability
|
|
189
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
190
|
+
of your accepting any such warranty or additional liability.
|
|
191
|
+
|
|
192
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# @hazeljs/guardrails
|
|
2
|
+
|
|
3
|
+
**Content safety, PII handling, and output validation for HazelJS AI applications.**
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@hazeljs/guardrails)
|
|
6
|
+
[](https://www.npmjs.com/package/@hazeljs/guardrails)
|
|
7
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
8
|
+
|
|
9
|
+
## Why Guardrails?
|
|
10
|
+
|
|
11
|
+
AI applications face unique security challenges: prompt injection, PII leakage, toxic output. Unlike LangChain or Vercel AI SDK, HazelJS provides **built-in guardrails** that plug into HTTP, AI, and agent layers—no separate middleware.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- **PII Detection & Redaction** — Email, phone, SSN, credit card (configurable entities)
|
|
16
|
+
- **Prompt Injection Detection** — Heuristic patterns (e.g. "ignore previous instructions", "jailbreak")
|
|
17
|
+
- **Toxicity Check** — Keyword blocklist for harmful content
|
|
18
|
+
- **Output Validation** — Schema validation and PII redaction on LLM responses
|
|
19
|
+
- **HTTP Integration** — GuardrailPipe and GuardrailInterceptor for routes
|
|
20
|
+
- **AI Integration** — @GuardrailInput and @GuardrailOutput decorators for @AITask
|
|
21
|
+
- **Agent Integration** — Automatic input/output guardrails for @hazeljs/agent tools
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install @hazeljs/guardrails
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Or with the HazelJS CLI:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
hazel add guardrails
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick Start
|
|
36
|
+
|
|
37
|
+
### 1. Import the Module
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
import { HazelModule } from '@hazeljs/core';
|
|
41
|
+
import { GuardrailsModule } from '@hazeljs/guardrails';
|
|
42
|
+
|
|
43
|
+
@HazelModule({
|
|
44
|
+
imports: [
|
|
45
|
+
GuardrailsModule.forRoot({
|
|
46
|
+
redactPIIByDefault: true,
|
|
47
|
+
blockInjectionByDefault: true,
|
|
48
|
+
blockToxicityByDefault: true,
|
|
49
|
+
}),
|
|
50
|
+
],
|
|
51
|
+
})
|
|
52
|
+
export class AppModule {}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### 2. Use with HTTP Routes
|
|
56
|
+
|
|
57
|
+
**GuardrailPipe** — Validate request body:
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { Controller, Post, Body, UsePipes } from '@hazeljs/core';
|
|
61
|
+
import { GuardrailPipe } from '@hazeljs/guardrails';
|
|
62
|
+
|
|
63
|
+
@Controller({ path: '/chat' })
|
|
64
|
+
export class ChatController {
|
|
65
|
+
@Post()
|
|
66
|
+
@UsePipes(GuardrailPipe)
|
|
67
|
+
async chat(@Body() body: { message: string }) {
|
|
68
|
+
return { reply: '...' };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**GuardrailInterceptor** — Validate input and output:
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
import { Controller, UseInterceptors } from '@hazeljs/core';
|
|
77
|
+
import { GuardrailInterceptor } from '@hazeljs/guardrails';
|
|
78
|
+
|
|
79
|
+
@Controller({ path: '/chat' })
|
|
80
|
+
@UseInterceptors(GuardrailInterceptor)
|
|
81
|
+
export class ChatController {
|
|
82
|
+
@Post()
|
|
83
|
+
async chat(@Body() body: { message: string }) {
|
|
84
|
+
return { reply: '...' };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### 3. Use with @AITask
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
import { Controller, Post, Body } from '@hazeljs/core';
|
|
93
|
+
import { AIService, AITask } from '@hazeljs/ai';
|
|
94
|
+
import { GuardrailsService, GuardrailInput, GuardrailOutput } from '@hazeljs/guardrails';
|
|
95
|
+
|
|
96
|
+
@Controller({ path: '/chat' })
|
|
97
|
+
export class ChatController {
|
|
98
|
+
constructor(private aiService: AIService, private guardrailsService: GuardrailsService) {}
|
|
99
|
+
|
|
100
|
+
@GuardrailInput()
|
|
101
|
+
@GuardrailOutput()
|
|
102
|
+
@AITask({ provider: 'openai', model: 'gpt-4' })
|
|
103
|
+
@Post()
|
|
104
|
+
async chat(@Body() body: { message: string }) {
|
|
105
|
+
return body.message;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### 4. Use with @hazeljs/agent
|
|
111
|
+
|
|
112
|
+
When both `GuardrailsModule` and `AgentModule` are imported, tool input and output are automatically validated:
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
@HazelModule({
|
|
116
|
+
imports: [
|
|
117
|
+
GuardrailsModule.forRoot(),
|
|
118
|
+
AgentModule.forRoot(),
|
|
119
|
+
],
|
|
120
|
+
})
|
|
121
|
+
export class AppModule {}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Configuration
|
|
125
|
+
|
|
126
|
+
| Option | Type | Default | Description |
|
|
127
|
+
|--------|------|---------|-------------|
|
|
128
|
+
| `piiEntities` | `PIIEntityType[]` | `['email','phone','ssn','credit_card']` | Entities to detect/redact |
|
|
129
|
+
| `redactPIIByDefault` | `boolean` | `false` | Redact PII in input by default |
|
|
130
|
+
| `blockInjectionByDefault` | `boolean` | `true` | Block prompt injection by default |
|
|
131
|
+
| `blockToxicityByDefault` | `boolean` | `true` | Block toxic content by default |
|
|
132
|
+
| `injectionBlocklist` | `string[]` | — | Custom injection patterns |
|
|
133
|
+
| `toxicityBlocklist` | `string[]` | — | Custom toxicity keywords |
|
|
134
|
+
|
|
135
|
+
## API
|
|
136
|
+
|
|
137
|
+
### GuardrailsService
|
|
138
|
+
|
|
139
|
+
- `checkInput(input, options?)` — Validate input, returns `{ allowed, modified?, violations? }`
|
|
140
|
+
- `checkOutput(output, options?)` — Validate output, returns `{ allowed, modified?, violations? }`
|
|
141
|
+
- `redactPII(text, entities?)` — Redact PII from text
|
|
142
|
+
|
|
143
|
+
### GuardrailViolationError
|
|
144
|
+
|
|
145
|
+
Thrown when content is blocked. Includes `violations` and `blockedReason`. Use an Exception Filter to map to HTTP 400.
|
|
146
|
+
|
|
147
|
+
### Use Cases
|
|
148
|
+
|
|
149
|
+
- **Customer support chatbot** — Block injection, redact PII, validate responses
|
|
150
|
+
- **Internal AI tools** — Ensure agent tools don't leak sensitive data
|
|
151
|
+
- **Public chat API** — GuardrailPipe on `/chat` to reject toxic or injection attempts
|
|
152
|
+
- **Compliance** — PII redaction for GDPR/CCPA, documented controls for audits
|
|
153
|
+
|
|
154
|
+
## Learn More
|
|
155
|
+
|
|
156
|
+
- [Documentation](https://hazeljs.com/docs/packages/guardrails)
|
|
157
|
+
- [@hazeljs/ai](https://hazeljs.com/docs/packages/ai) — AI integration
|
|
158
|
+
- [@hazeljs/agent](https://hazeljs.com/docs/packages/agent) — Agent runtime
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt injection detection (heuristic-based)
|
|
3
|
+
*/
|
|
4
|
+
export interface InjectionCheckOptions {
|
|
5
|
+
customPatterns?: RegExp[];
|
|
6
|
+
useDefaults?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export declare function checkPromptInjection(text: string, options?: InjectionCheckOptions): {
|
|
9
|
+
detected: boolean;
|
|
10
|
+
matchedPattern?: string;
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=injection.check.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"injection.check.d.ts","sourceRoot":"","sources":["../../src/checks/injection.check.ts"],"names":[],"mappings":"AAAA;;GAEG;AAqBH,MAAM,WAAW,qBAAqB;IACpC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,qBAA0B,GAClC;IAAE,QAAQ,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,CAchD"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Prompt injection detection (heuristic-based)
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.checkPromptInjection = checkPromptInjection;
|
|
7
|
+
const DEFAULT_INJECTION_PATTERNS = [
|
|
8
|
+
/\bignore\s+(?:all\s+)?(?:previous|above|prior)\s+instructions?\b/i,
|
|
9
|
+
/\bdisregard\s+(?:all\s+)?(?:previous|above|prior)\b/i,
|
|
10
|
+
/\bforget\s+(?:everything|all)\s+(?:you\s+)?(?:have\s+)?(?:been\s+)?(?:told|taught)\b/i,
|
|
11
|
+
/\b(?:new|different)\s+instructions?\s*:\s*/i,
|
|
12
|
+
/\bsystem\s*:\s*/i,
|
|
13
|
+
/\b(?:user|assistant)\s*:\s*/i,
|
|
14
|
+
/\b###\s*(?:system|instruction|prompt)\s*:/i,
|
|
15
|
+
/\b\[INST\]\b/i,
|
|
16
|
+
/\b\[\/INST\]\b/i,
|
|
17
|
+
/\boverride\s+(?:your|the)\s+(?:instructions?|rules?)\b/i,
|
|
18
|
+
/\bpretend\s+(?:you\s+)?(?:are|to\s+be)\b/i,
|
|
19
|
+
/\bact\s+as\s+if\b/i,
|
|
20
|
+
/\byou\s+are\s+now\s+(?:a|an)\b/i,
|
|
21
|
+
/\b(?:jailbreak|jail\s*break)\b/i,
|
|
22
|
+
/\bDAN\s+mode\b/i,
|
|
23
|
+
/\bdeveloper\s+mode\b/i,
|
|
24
|
+
];
|
|
25
|
+
function checkPromptInjection(text, options = {}) {
|
|
26
|
+
const { customPatterns = [], useDefaults = true } = options;
|
|
27
|
+
const patterns = useDefaults
|
|
28
|
+
? [...DEFAULT_INJECTION_PATTERNS, ...customPatterns]
|
|
29
|
+
: customPatterns;
|
|
30
|
+
for (const pattern of patterns) {
|
|
31
|
+
if (pattern.test(text)) {
|
|
32
|
+
return { detected: true, matchedPattern: pattern.source };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { detected: false };
|
|
36
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PII detection and redaction
|
|
3
|
+
*/
|
|
4
|
+
import type { PIIEntityType } from '../guardrails.types';
|
|
5
|
+
export declare function detectPII(text: string, entityTypes?: PIIEntityType[]): {
|
|
6
|
+
entities: PIIEntityType[];
|
|
7
|
+
matches: string[];
|
|
8
|
+
};
|
|
9
|
+
export declare function redactPII(text: string, entityTypes?: PIIEntityType[]): string;
|
|
10
|
+
//# sourceMappingURL=pii.check.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pii.check.d.ts","sourceRoot":"","sources":["../../src/checks/pii.check.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAgBzD,wBAAgB,SAAS,CACvB,IAAI,EAAE,MAAM,EACZ,WAAW,GAAE,aAAa,EAA6C,GACtE;IAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAclD;AAED,wBAAgB,SAAS,CACvB,IAAI,EAAE,MAAM,EACZ,WAAW,GAAE,aAAa,EAA6C,GACtE,MAAM,CAUR"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* PII detection and redaction
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.detectPII = detectPII;
|
|
7
|
+
exports.redactPII = redactPII;
|
|
8
|
+
const PII_PATTERNS = {
|
|
9
|
+
email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
|
|
10
|
+
phone: /\b(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b|\b\+?[0-9]{10,15}\b/g,
|
|
11
|
+
ssn: /\b\d{3}-\d{2}-\d{4}\b|\b\d{9}\b/g,
|
|
12
|
+
credit_card: /\b(?:\d{4}[-.\s]?){3}\d{4}\b|\b\d{13,19}\b/g,
|
|
13
|
+
};
|
|
14
|
+
const PII_REPLACEMENTS = {
|
|
15
|
+
email: '[EMAIL_REDACTED]',
|
|
16
|
+
phone: '[PHONE_REDACTED]',
|
|
17
|
+
ssn: '[SSN_REDACTED]',
|
|
18
|
+
credit_card: '[CARD_REDACTED]',
|
|
19
|
+
};
|
|
20
|
+
function detectPII(text, entityTypes = ['email', 'phone', 'ssn', 'credit_card']) {
|
|
21
|
+
const entities = [];
|
|
22
|
+
const matches = [];
|
|
23
|
+
for (const entityType of entityTypes) {
|
|
24
|
+
const pattern = PII_PATTERNS[entityType];
|
|
25
|
+
const found = text.match(pattern);
|
|
26
|
+
if (found) {
|
|
27
|
+
entities.push(entityType);
|
|
28
|
+
matches.push(...found);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return { entities, matches };
|
|
32
|
+
}
|
|
33
|
+
function redactPII(text, entityTypes = ['email', 'phone', 'ssn', 'credit_card']) {
|
|
34
|
+
let result = text;
|
|
35
|
+
for (const entityType of entityTypes) {
|
|
36
|
+
const pattern = PII_PATTERNS[entityType];
|
|
37
|
+
const replacement = PII_REPLACEMENTS[entityType];
|
|
38
|
+
result = result.replace(pattern, replacement);
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Toxicity detection (keyword blocklist)
|
|
3
|
+
*/
|
|
4
|
+
export interface ToxicityCheckOptions {
|
|
5
|
+
customPatterns?: RegExp[];
|
|
6
|
+
customKeywords?: string[];
|
|
7
|
+
useDefaults?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function checkToxicity(text: string, options?: ToxicityCheckOptions): {
|
|
10
|
+
detected: boolean;
|
|
11
|
+
matchedPattern?: string;
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=toxicity.check.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toxicity.check.d.ts","sourceRoot":"","sources":["../../src/checks/toxicity.check.ts"],"names":[],"mappings":"AAAA;;GAEG;AAWH,MAAM,WAAW,oBAAoB;IACnC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,wBAAgB,aAAa,CAC3B,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,oBAAyB,GACjC;IAAE,QAAQ,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,CAoBhD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Toxicity detection (keyword blocklist)
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.checkToxicity = checkToxicity;
|
|
7
|
+
const DEFAULT_TOXICITY_PATTERNS = [
|
|
8
|
+
/\b(?:kill|murder|suicide|self[- ]?harm)\b/i,
|
|
9
|
+
/\b(?:bomb|explosive|terrorist)\b/i,
|
|
10
|
+
/\b(?:hate\s+speech|racial\s+slur)\b/i,
|
|
11
|
+
/\b(?:child\s+abuse|pedophil)\b/i,
|
|
12
|
+
/\b(?:illegal\s+drugs?|how\s+to\s+make\s+meth)\b/i,
|
|
13
|
+
/\b(?:weapon\s+of\s+mass\s+destruction)\b/i,
|
|
14
|
+
];
|
|
15
|
+
function checkToxicity(text, options = {}) {
|
|
16
|
+
const { customPatterns = [], customKeywords = [], useDefaults = true } = options;
|
|
17
|
+
const patterns = useDefaults ? [...DEFAULT_TOXICITY_PATTERNS, ...customPatterns] : customPatterns;
|
|
18
|
+
for (const pattern of patterns) {
|
|
19
|
+
if (pattern.test(text)) {
|
|
20
|
+
return { detected: true, matchedPattern: pattern.source };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
for (const keyword of customKeywords) {
|
|
24
|
+
const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
25
|
+
const regex = new RegExp(`\\b${escaped}\\b`, 'i');
|
|
26
|
+
if (regex.test(text)) {
|
|
27
|
+
return { detected: true, matchedPattern: keyword };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { detected: false };
|
|
31
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @GuardrailInput - Run input guardrails before method execution
|
|
3
|
+
*/
|
|
4
|
+
import 'reflect-metadata';
|
|
5
|
+
import type { GuardrailInputOptions } from '../guardrails.types';
|
|
6
|
+
export declare function GuardrailInput(options?: GuardrailInputOptions): MethodDecorator;
|
|
7
|
+
export declare function getGuardrailInputMetadata(target: object, propertyKey: string | symbol): GuardrailInputOptions | undefined;
|
|
8
|
+
//# sourceMappingURL=guardrail-input.decorator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail-input.decorator.d.ts","sourceRoot":"","sources":["../../src/decorators/guardrail-input.decorator.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAIjE,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,eAAe,CA8C/E;AAED,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAAG,MAAM,GAC3B,qBAAqB,GAAG,SAAS,CAEnC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @GuardrailInput - Run input guardrails before method execution
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GuardrailInput = GuardrailInput;
|
|
7
|
+
exports.getGuardrailInputMetadata = getGuardrailInputMetadata;
|
|
8
|
+
require("reflect-metadata");
|
|
9
|
+
const guardrail_violation_error_1 = require("../errors/guardrail-violation.error");
|
|
10
|
+
const GUARDRAIL_INPUT_METADATA_KEY = 'hazel:guardrail-input';
|
|
11
|
+
function GuardrailInput(options) {
|
|
12
|
+
return (target, propertyKey, descriptor) => {
|
|
13
|
+
Reflect.defineMetadata(GUARDRAIL_INPUT_METADATA_KEY, options ?? {}, target, propertyKey);
|
|
14
|
+
const original = descriptor.value;
|
|
15
|
+
descriptor.value = async function (...args) {
|
|
16
|
+
const guardrailsService = this
|
|
17
|
+
.guardrailsService;
|
|
18
|
+
if (!guardrailsService) {
|
|
19
|
+
throw new Error('GuardrailsService not found. Inject GuardrailsService in the constructor and import GuardrailsModule.');
|
|
20
|
+
}
|
|
21
|
+
const opts = Reflect.getMetadata(GUARDRAIL_INPUT_METADATA_KEY, target, propertyKey);
|
|
22
|
+
const input = args[0];
|
|
23
|
+
const result = guardrailsService.checkInput(input, opts);
|
|
24
|
+
if (!result.allowed) {
|
|
25
|
+
throw new guardrail_violation_error_1.GuardrailViolationError(result.blockedReason ?? 'Input blocked by guardrails', result.violations, result.blockedReason);
|
|
26
|
+
}
|
|
27
|
+
if (result.modified !== undefined) {
|
|
28
|
+
args[0] = result.modified;
|
|
29
|
+
}
|
|
30
|
+
return original.apply(this, args);
|
|
31
|
+
};
|
|
32
|
+
return descriptor;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function getGuardrailInputMetadata(target, propertyKey) {
|
|
36
|
+
return Reflect.getMetadata(GUARDRAIL_INPUT_METADATA_KEY, target, propertyKey);
|
|
37
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @GuardrailOutput - Run output guardrails after method execution
|
|
3
|
+
*/
|
|
4
|
+
import 'reflect-metadata';
|
|
5
|
+
import type { GuardrailOutputOptions } from '../guardrails.types';
|
|
6
|
+
export declare function GuardrailOutput(options?: GuardrailOutputOptions): MethodDecorator;
|
|
7
|
+
export declare function getGuardrailOutputMetadata(target: object, propertyKey: string | symbol): GuardrailOutputOptions | undefined;
|
|
8
|
+
//# sourceMappingURL=guardrail-output.decorator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail-output.decorator.d.ts","sourceRoot":"","sources":["../../src/decorators/guardrail-output.decorator.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAIlE,wBAAgB,eAAe,CAAC,OAAO,CAAC,EAAE,sBAAsB,GAAG,eAAe,CA2CjF;AAED,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAAG,MAAM,GAC3B,sBAAsB,GAAG,SAAS,CAEpC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @GuardrailOutput - Run output guardrails after method execution
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GuardrailOutput = GuardrailOutput;
|
|
7
|
+
exports.getGuardrailOutputMetadata = getGuardrailOutputMetadata;
|
|
8
|
+
require("reflect-metadata");
|
|
9
|
+
const guardrail_violation_error_1 = require("../errors/guardrail-violation.error");
|
|
10
|
+
const GUARDRAIL_OUTPUT_METADATA_KEY = 'hazel:guardrail-output';
|
|
11
|
+
function GuardrailOutput(options) {
|
|
12
|
+
return (target, propertyKey, descriptor) => {
|
|
13
|
+
Reflect.defineMetadata(GUARDRAIL_OUTPUT_METADATA_KEY, options ?? {}, target, propertyKey);
|
|
14
|
+
const original = descriptor.value;
|
|
15
|
+
descriptor.value = async function (...args) {
|
|
16
|
+
const guardrailsService = this
|
|
17
|
+
.guardrailsService;
|
|
18
|
+
if (!guardrailsService) {
|
|
19
|
+
throw new Error('GuardrailsService not found. Inject GuardrailsService in the constructor and import GuardrailsModule.');
|
|
20
|
+
}
|
|
21
|
+
const result = await original.apply(this, args);
|
|
22
|
+
const opts = Reflect.getMetadata(GUARDRAIL_OUTPUT_METADATA_KEY, target, propertyKey);
|
|
23
|
+
const outputResult = guardrailsService.checkOutput(result, opts);
|
|
24
|
+
if (!outputResult.allowed) {
|
|
25
|
+
throw new guardrail_violation_error_1.GuardrailViolationError(outputResult.blockedReason ?? 'Output blocked by guardrails', outputResult.violations, outputResult.blockedReason);
|
|
26
|
+
}
|
|
27
|
+
return outputResult.modified ?? result;
|
|
28
|
+
};
|
|
29
|
+
return descriptor;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function getGuardrailOutputMetadata(target, propertyKey) {
|
|
33
|
+
return Reflect.getMetadata(GUARDRAIL_OUTPUT_METADATA_KEY, target, propertyKey);
|
|
34
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GuardrailViolationError - Thrown when guardrail check fails
|
|
3
|
+
*/
|
|
4
|
+
export declare class GuardrailViolationError extends Error {
|
|
5
|
+
readonly violations?: string[] | undefined;
|
|
6
|
+
readonly blockedReason?: string | undefined;
|
|
7
|
+
constructor(message: string, violations?: string[] | undefined, blockedReason?: string | undefined);
|
|
8
|
+
toJSON(): {
|
|
9
|
+
message: string;
|
|
10
|
+
violations?: string[];
|
|
11
|
+
blockedReason?: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=guardrail-violation.error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail-violation.error.d.ts","sourceRoot":"","sources":["../../src/errors/guardrail-violation.error.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,qBAAa,uBAAwB,SAAQ,KAAK;aAG9B,UAAU,CAAC,EAAE,MAAM,EAAE;aACrB,aAAa,CAAC,EAAE,MAAM;gBAFtC,OAAO,EAAE,MAAM,EACC,UAAU,CAAC,EAAE,MAAM,EAAE,YAAA,EACrB,aAAa,CAAC,EAAE,MAAM,YAAA;IAOxC,MAAM,IAAI;QACR,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;QACtB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB;CAOF"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* GuardrailViolationError - Thrown when guardrail check fails
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GuardrailViolationError = void 0;
|
|
7
|
+
class GuardrailViolationError extends Error {
|
|
8
|
+
constructor(message, violations, blockedReason) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.violations = violations;
|
|
11
|
+
this.blockedReason = blockedReason;
|
|
12
|
+
this.name = 'GuardrailViolationError';
|
|
13
|
+
Object.setPrototypeOf(this, GuardrailViolationError.prototype);
|
|
14
|
+
}
|
|
15
|
+
toJSON() {
|
|
16
|
+
return {
|
|
17
|
+
message: this.message,
|
|
18
|
+
violations: this.violations,
|
|
19
|
+
blockedReason: this.blockedReason,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.GuardrailViolationError = GuardrailViolationError;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GuardrailsModule - Content safety for AI applications
|
|
3
|
+
*/
|
|
4
|
+
import type { GuardrailsModuleOptions } from './guardrails.types';
|
|
5
|
+
/** Token for optional injection (e.g. in @hazeljs/agent) */
|
|
6
|
+
export declare const GUARDRAILS_SERVICE_TOKEN = "GuardrailsService";
|
|
7
|
+
export declare class GuardrailsModule {
|
|
8
|
+
private static options;
|
|
9
|
+
static forRoot(options?: GuardrailsModuleOptions): typeof GuardrailsModule;
|
|
10
|
+
static getOptions(): GuardrailsModuleOptions;
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=guardrails.module.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrails.module.d.ts","sourceRoot":"","sources":["../src/guardrails.module.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAElE,4DAA4D;AAC5D,eAAO,MAAM,wBAAwB,sBAAsB,CAAC;AAO5D,qBASa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAC,OAAO,CAA+B;IAErD,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,gBAAgB;IAQ1E,MAAM,CAAC,UAAU,IAAI,uBAAuB;CAG7C"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* GuardrailsModule - Content safety for AI applications
|
|
4
|
+
*/
|
|
5
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
6
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
7
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
8
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
9
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
10
|
+
};
|
|
11
|
+
var GuardrailsModule_1;
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.GuardrailsModule = exports.GUARDRAILS_SERVICE_TOKEN = void 0;
|
|
14
|
+
const core_1 = require("@hazeljs/core");
|
|
15
|
+
const guardrails_service_1 = require("./guardrails.service");
|
|
16
|
+
const guardrail_pipe_1 = require("./pipes/guardrail.pipe");
|
|
17
|
+
const guardrail_interceptor_1 = require("./interceptors/guardrail.interceptor");
|
|
18
|
+
/** Token for optional injection (e.g. in @hazeljs/agent) */
|
|
19
|
+
exports.GUARDRAILS_SERVICE_TOKEN = 'GuardrailsService';
|
|
20
|
+
const guardrailsServiceProvider = {
|
|
21
|
+
token: exports.GUARDRAILS_SERVICE_TOKEN,
|
|
22
|
+
useClass: guardrails_service_1.GuardrailsService,
|
|
23
|
+
};
|
|
24
|
+
let GuardrailsModule = GuardrailsModule_1 = class GuardrailsModule {
|
|
25
|
+
static forRoot(options) {
|
|
26
|
+
GuardrailsModule_1.options = options ?? {};
|
|
27
|
+
if (options) {
|
|
28
|
+
guardrails_service_1.GuardrailsService.configure(options);
|
|
29
|
+
}
|
|
30
|
+
return GuardrailsModule_1;
|
|
31
|
+
}
|
|
32
|
+
static getOptions() {
|
|
33
|
+
return GuardrailsModule_1.options;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
exports.GuardrailsModule = GuardrailsModule;
|
|
37
|
+
GuardrailsModule.options = {};
|
|
38
|
+
exports.GuardrailsModule = GuardrailsModule = GuardrailsModule_1 = __decorate([
|
|
39
|
+
(0, core_1.HazelModule)({
|
|
40
|
+
providers: [
|
|
41
|
+
guardrails_service_1.GuardrailsService,
|
|
42
|
+
guardrail_pipe_1.GuardrailPipe,
|
|
43
|
+
guardrail_interceptor_1.GuardrailInterceptor,
|
|
44
|
+
guardrailsServiceProvider,
|
|
45
|
+
],
|
|
46
|
+
exports: [guardrails_service_1.GuardrailsService, guardrail_pipe_1.GuardrailPipe, guardrail_interceptor_1.GuardrailInterceptor],
|
|
47
|
+
})
|
|
48
|
+
], GuardrailsModule);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GuardrailsService - Content safety, PII, and output validation
|
|
3
|
+
*/
|
|
4
|
+
import type { GuardrailInputOptions, GuardrailOutputOptions, GuardrailResult, GuardrailsModuleOptions, PIIEntityType } from './guardrails.types';
|
|
5
|
+
export declare class GuardrailsService {
|
|
6
|
+
private static staticOptions;
|
|
7
|
+
private options;
|
|
8
|
+
constructor(options?: GuardrailsModuleOptions);
|
|
9
|
+
static configure(options: GuardrailsModuleOptions): void;
|
|
10
|
+
configure(options: GuardrailsModuleOptions): void;
|
|
11
|
+
/**
|
|
12
|
+
* Check input for guardrail violations
|
|
13
|
+
*/
|
|
14
|
+
checkInput(input: string | object, options?: GuardrailInputOptions): GuardrailResult;
|
|
15
|
+
/**
|
|
16
|
+
* Check output for guardrail violations
|
|
17
|
+
*/
|
|
18
|
+
checkOutput(output: string | object, options?: GuardrailOutputOptions): GuardrailResult;
|
|
19
|
+
/**
|
|
20
|
+
* Redact PII from text
|
|
21
|
+
*/
|
|
22
|
+
redactPII(text: string, entities?: PIIEntityType[]): string;
|
|
23
|
+
private mergeInputOptions;
|
|
24
|
+
private extractText;
|
|
25
|
+
private applyRedactionToObject;
|
|
26
|
+
private validateSchema;
|
|
27
|
+
private validateAgainstSchema;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=guardrails.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrails.service.d.ts","sourceRoot":"","sources":["../src/guardrails.service.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EACV,qBAAqB,EACrB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,aAAa,EACd,MAAM,oBAAoB,CAAC;AAO5B,qBACa,iBAAiB;IAC5B,OAAO,CAAC,MAAM,CAAC,aAAa,CAA+B;IAC3D,OAAO,CAAC,OAAO,CAA+B;gBAElC,OAAO,CAAC,EAAE,uBAAuB;IAI7C,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAIxD,SAAS,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAIjD;;OAEG;IACH,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,qBAAqB,GAAG,eAAe;IAqDpF;;OAEG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,sBAAsB,GAAG,eAAe;IAiDvF;;OAEG;IACH,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,aAAa,EAAE,GAAG,MAAM;IAK3D,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,WAAW;IAmBnB,OAAO,CAAC,sBAAsB;IAU9B,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,qBAAqB;CAoB9B"}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* GuardrailsService - Content safety, PII, and output validation
|
|
4
|
+
*/
|
|
5
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
6
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
7
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
8
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
9
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
10
|
+
};
|
|
11
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
12
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
13
|
+
};
|
|
14
|
+
var GuardrailsService_1;
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.GuardrailsService = void 0;
|
|
17
|
+
const core_1 = require("@hazeljs/core");
|
|
18
|
+
const core_2 = require("@hazeljs/core");
|
|
19
|
+
const pii_check_1 = require("./checks/pii.check");
|
|
20
|
+
const injection_check_1 = require("./checks/injection.check");
|
|
21
|
+
const toxicity_check_1 = require("./checks/toxicity.check");
|
|
22
|
+
const DEFAULT_ENTITY_TYPES = ['email', 'phone', 'ssn', 'credit_card'];
|
|
23
|
+
let GuardrailsService = GuardrailsService_1 = class GuardrailsService {
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.options = {};
|
|
26
|
+
this.options = options ?? { ...GuardrailsService_1.staticOptions };
|
|
27
|
+
}
|
|
28
|
+
static configure(options) {
|
|
29
|
+
GuardrailsService_1.staticOptions = { ...GuardrailsService_1.staticOptions, ...options };
|
|
30
|
+
}
|
|
31
|
+
configure(options) {
|
|
32
|
+
this.options = { ...this.options, ...options };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Check input for guardrail violations
|
|
36
|
+
*/
|
|
37
|
+
checkInput(input, options) {
|
|
38
|
+
const opts = this.mergeInputOptions(options);
|
|
39
|
+
const text = this.extractText(input);
|
|
40
|
+
if (!text) {
|
|
41
|
+
return { allowed: true };
|
|
42
|
+
}
|
|
43
|
+
const violations = [];
|
|
44
|
+
let modified;
|
|
45
|
+
if (opts.blockInjection) {
|
|
46
|
+
const injection = (0, injection_check_1.checkPromptInjection)(text);
|
|
47
|
+
if (injection.detected) {
|
|
48
|
+
return {
|
|
49
|
+
allowed: false,
|
|
50
|
+
violations: ['prompt_injection'],
|
|
51
|
+
blockedReason: 'Potential prompt injection detected',
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (opts.blockToxicity) {
|
|
56
|
+
const toxicity = (0, toxicity_check_1.checkToxicity)(text, {
|
|
57
|
+
customKeywords: this.options.toxicityBlocklist,
|
|
58
|
+
});
|
|
59
|
+
if (toxicity.detected) {
|
|
60
|
+
return {
|
|
61
|
+
allowed: false,
|
|
62
|
+
violations: ['toxicity'],
|
|
63
|
+
blockedReason: 'Toxic content detected',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (opts.redactPII) {
|
|
68
|
+
const entityTypes = opts.entityTypes ?? this.options.piiEntities ?? DEFAULT_ENTITY_TYPES;
|
|
69
|
+
const piiDetected = (0, pii_check_1.detectPII)(text, entityTypes);
|
|
70
|
+
if (piiDetected.entities.length > 0) {
|
|
71
|
+
const redacted = (0, pii_check_1.redactPII)(text, entityTypes);
|
|
72
|
+
modified =
|
|
73
|
+
typeof input === 'string' ? redacted : this.applyRedactionToObject(input, entityTypes);
|
|
74
|
+
violations.push('pii_redacted');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
allowed: true,
|
|
79
|
+
modified,
|
|
80
|
+
violations: violations.length > 0 ? violations : undefined,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Check output for guardrail violations
|
|
85
|
+
*/
|
|
86
|
+
checkOutput(output, options) {
|
|
87
|
+
const text = this.extractText(output);
|
|
88
|
+
if (!text) {
|
|
89
|
+
return { allowed: true };
|
|
90
|
+
}
|
|
91
|
+
if (options?.allowPII !== true) {
|
|
92
|
+
const entityTypes = this.options.piiEntities ?? DEFAULT_ENTITY_TYPES;
|
|
93
|
+
const piiDetected = (0, pii_check_1.detectPII)(text, entityTypes);
|
|
94
|
+
if (piiDetected.entities.length > 0) {
|
|
95
|
+
const redacted = (0, pii_check_1.redactPII)(text, entityTypes);
|
|
96
|
+
const modified = typeof output === 'string'
|
|
97
|
+
? redacted
|
|
98
|
+
: this.applyRedactionToObject(output, entityTypes);
|
|
99
|
+
return {
|
|
100
|
+
allowed: true,
|
|
101
|
+
modified,
|
|
102
|
+
violations: ['pii_redacted'],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const toxicity = (0, toxicity_check_1.checkToxicity)(text, {
|
|
107
|
+
customKeywords: this.options.toxicityBlocklist,
|
|
108
|
+
});
|
|
109
|
+
if (toxicity.detected) {
|
|
110
|
+
return {
|
|
111
|
+
allowed: false,
|
|
112
|
+
violations: ['toxicity'],
|
|
113
|
+
blockedReason: 'Toxic content in output',
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (options?.schema) {
|
|
117
|
+
const schemaResult = this.validateSchema(output, options.schema);
|
|
118
|
+
if (!schemaResult.valid) {
|
|
119
|
+
return {
|
|
120
|
+
allowed: false,
|
|
121
|
+
violations: ['schema_validation'],
|
|
122
|
+
blockedReason: schemaResult.error,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { allowed: true };
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Redact PII from text
|
|
130
|
+
*/
|
|
131
|
+
redactPII(text, entities) {
|
|
132
|
+
const entityTypes = entities ?? this.options.piiEntities ?? DEFAULT_ENTITY_TYPES;
|
|
133
|
+
return (0, pii_check_1.redactPII)(text, entityTypes);
|
|
134
|
+
}
|
|
135
|
+
mergeInputOptions(options) {
|
|
136
|
+
return {
|
|
137
|
+
entityTypes: options?.entityTypes ?? this.options.piiEntities ?? DEFAULT_ENTITY_TYPES,
|
|
138
|
+
redactPII: options?.redactPII ?? this.options.redactPIIByDefault ?? false,
|
|
139
|
+
blockInjection: options?.blockInjection ?? this.options.blockInjectionByDefault ?? true,
|
|
140
|
+
blockToxicity: options?.blockToxicity ?? this.options.blockToxicityByDefault ?? true,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
extractText(input) {
|
|
144
|
+
if (typeof input === 'string') {
|
|
145
|
+
return (0, core_2.sanitizeString)(input);
|
|
146
|
+
}
|
|
147
|
+
if (input && typeof input === 'object') {
|
|
148
|
+
if ('message' in input && typeof input.message === 'string') {
|
|
149
|
+
return (0, core_2.sanitizeString)(input.message);
|
|
150
|
+
}
|
|
151
|
+
if ('prompt' in input && typeof input.prompt === 'string') {
|
|
152
|
+
return (0, core_2.sanitizeString)(input.prompt);
|
|
153
|
+
}
|
|
154
|
+
if ('content' in input && typeof input.content === 'string') {
|
|
155
|
+
return (0, core_2.sanitizeString)(input.content);
|
|
156
|
+
}
|
|
157
|
+
return (0, core_2.sanitizeString)(JSON.stringify(input));
|
|
158
|
+
}
|
|
159
|
+
return '';
|
|
160
|
+
}
|
|
161
|
+
applyRedactionToObject(obj, entityTypes) {
|
|
162
|
+
const str = JSON.stringify(obj);
|
|
163
|
+
const redacted = (0, pii_check_1.redactPII)(str, entityTypes);
|
|
164
|
+
try {
|
|
165
|
+
return JSON.parse(redacted);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return { _redacted: redacted };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
validateSchema(output, schema) {
|
|
172
|
+
if (typeof output === 'string') {
|
|
173
|
+
try {
|
|
174
|
+
const parsed = JSON.parse(output);
|
|
175
|
+
return this.validateAgainstSchema(parsed, schema);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return { valid: false, error: 'Output is not valid JSON' };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return this.validateAgainstSchema(output, schema);
|
|
182
|
+
}
|
|
183
|
+
validateAgainstSchema(data, schema) {
|
|
184
|
+
if (typeof schema !== 'object' || schema === null) {
|
|
185
|
+
return { valid: true };
|
|
186
|
+
}
|
|
187
|
+
const s = schema;
|
|
188
|
+
if (s.type === 'object' && s.properties) {
|
|
189
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
190
|
+
return { valid: false, error: 'Expected object' };
|
|
191
|
+
}
|
|
192
|
+
for (const [key, propSchema] of Object.entries(s.properties)) {
|
|
193
|
+
const prop = propSchema;
|
|
194
|
+
if (prop?.required && !(key in data)) {
|
|
195
|
+
return { valid: false, error: `Missing required property: ${key}` };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return { valid: true };
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
exports.GuardrailsService = GuardrailsService;
|
|
203
|
+
GuardrailsService.staticOptions = {};
|
|
204
|
+
exports.GuardrailsService = GuardrailsService = GuardrailsService_1 = __decorate([
|
|
205
|
+
(0, core_1.Injectable)(),
|
|
206
|
+
__metadata("design:paramtypes", [Object])
|
|
207
|
+
], GuardrailsService);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hazeljs/guardrails - Types and interfaces
|
|
3
|
+
*/
|
|
4
|
+
export type PIIEntityType = 'email' | 'phone' | 'ssn' | 'credit_card';
|
|
5
|
+
export interface GuardrailInputOptions {
|
|
6
|
+
entityTypes?: PIIEntityType[];
|
|
7
|
+
redactPII?: boolean;
|
|
8
|
+
blockInjection?: boolean;
|
|
9
|
+
blockToxicity?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface GuardrailOutputOptions {
|
|
12
|
+
allowPII?: boolean;
|
|
13
|
+
schema?: object;
|
|
14
|
+
}
|
|
15
|
+
export interface GuardrailResult {
|
|
16
|
+
allowed: boolean;
|
|
17
|
+
modified?: string | object;
|
|
18
|
+
violations?: string[];
|
|
19
|
+
blockedReason?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface GuardrailsModuleOptions {
|
|
22
|
+
piiEntities?: PIIEntityType[];
|
|
23
|
+
injectionBlocklist?: string[];
|
|
24
|
+
toxicityBlocklist?: string[];
|
|
25
|
+
redactPIIByDefault?: boolean;
|
|
26
|
+
blockInjectionByDefault?: boolean;
|
|
27
|
+
blockToxicityByDefault?: boolean;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=guardrails.types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrails.types.d.ts","sourceRoot":"","sources":["../src/guardrails.types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,OAAO,GAAG,KAAK,GAAG,aAAa,CAAC;AAEtE,MAAM,WAAW,qBAAqB;IACpC,WAAW,CAAC,EAAE,aAAa,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,uBAAuB;IACtC,WAAW,CAAC,EAAE,aAAa,EAAE,CAAC;IAC9B,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hazeljs/guardrails - Content safety, PII handling, and output validation
|
|
3
|
+
*/
|
|
4
|
+
export { GuardrailsModule, GUARDRAILS_SERVICE_TOKEN } from './guardrails.module';
|
|
5
|
+
export { GuardrailsService } from './guardrails.service';
|
|
6
|
+
export { GuardrailPipe } from './pipes/guardrail.pipe';
|
|
7
|
+
export { GuardrailInterceptor } from './interceptors/guardrail.interceptor';
|
|
8
|
+
export { GuardrailInput, getGuardrailInputMetadata } from './decorators/guardrail-input.decorator';
|
|
9
|
+
export { GuardrailOutput, getGuardrailOutputMetadata, } from './decorators/guardrail-output.decorator';
|
|
10
|
+
export { GuardrailViolationError } from './errors/guardrail-violation.error';
|
|
11
|
+
export type { GuardrailInputOptions, GuardrailOutputOptions, GuardrailResult, GuardrailsModuleOptions, PIIEntityType, } from './guardrails.types';
|
|
12
|
+
export type { GuardrailPipeOptions } from './pipes/guardrail.pipe';
|
|
13
|
+
export type { GuardrailInterceptorOptions } from './interceptors/guardrail.interceptor';
|
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnG,OAAO,EACL,eAAe,EACf,0BAA0B,GAC3B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAE7E,YAAY,EACV,qBAAqB,EACrB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,aAAa,GACd,MAAM,oBAAoB,CAAC;AAE5B,YAAY,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACnE,YAAY,EAAE,2BAA2B,EAAE,MAAM,sCAAsC,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @hazeljs/guardrails - Content safety, PII handling, and output validation
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GuardrailViolationError = exports.getGuardrailOutputMetadata = exports.GuardrailOutput = exports.getGuardrailInputMetadata = exports.GuardrailInput = exports.GuardrailInterceptor = exports.GuardrailPipe = exports.GuardrailsService = exports.GUARDRAILS_SERVICE_TOKEN = exports.GuardrailsModule = void 0;
|
|
7
|
+
var guardrails_module_1 = require("./guardrails.module");
|
|
8
|
+
Object.defineProperty(exports, "GuardrailsModule", { enumerable: true, get: function () { return guardrails_module_1.GuardrailsModule; } });
|
|
9
|
+
Object.defineProperty(exports, "GUARDRAILS_SERVICE_TOKEN", { enumerable: true, get: function () { return guardrails_module_1.GUARDRAILS_SERVICE_TOKEN; } });
|
|
10
|
+
var guardrails_service_1 = require("./guardrails.service");
|
|
11
|
+
Object.defineProperty(exports, "GuardrailsService", { enumerable: true, get: function () { return guardrails_service_1.GuardrailsService; } });
|
|
12
|
+
var guardrail_pipe_1 = require("./pipes/guardrail.pipe");
|
|
13
|
+
Object.defineProperty(exports, "GuardrailPipe", { enumerable: true, get: function () { return guardrail_pipe_1.GuardrailPipe; } });
|
|
14
|
+
var guardrail_interceptor_1 = require("./interceptors/guardrail.interceptor");
|
|
15
|
+
Object.defineProperty(exports, "GuardrailInterceptor", { enumerable: true, get: function () { return guardrail_interceptor_1.GuardrailInterceptor; } });
|
|
16
|
+
var guardrail_input_decorator_1 = require("./decorators/guardrail-input.decorator");
|
|
17
|
+
Object.defineProperty(exports, "GuardrailInput", { enumerable: true, get: function () { return guardrail_input_decorator_1.GuardrailInput; } });
|
|
18
|
+
Object.defineProperty(exports, "getGuardrailInputMetadata", { enumerable: true, get: function () { return guardrail_input_decorator_1.getGuardrailInputMetadata; } });
|
|
19
|
+
var guardrail_output_decorator_1 = require("./decorators/guardrail-output.decorator");
|
|
20
|
+
Object.defineProperty(exports, "GuardrailOutput", { enumerable: true, get: function () { return guardrail_output_decorator_1.GuardrailOutput; } });
|
|
21
|
+
Object.defineProperty(exports, "getGuardrailOutputMetadata", { enumerable: true, get: function () { return guardrail_output_decorator_1.getGuardrailOutputMetadata; } });
|
|
22
|
+
var guardrail_violation_error_1 = require("./errors/guardrail-violation.error");
|
|
23
|
+
Object.defineProperty(exports, "GuardrailViolationError", { enumerable: true, get: function () { return guardrail_violation_error_1.GuardrailViolationError; } });
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GuardrailInterceptor - Input/output guardrails for HTTP requests
|
|
3
|
+
*/
|
|
4
|
+
import type { Interceptor } from '@hazeljs/core';
|
|
5
|
+
import type { RequestContext } from '@hazeljs/core';
|
|
6
|
+
import { GuardrailsService } from '../guardrails.service';
|
|
7
|
+
import type { GuardrailInputOptions, GuardrailOutputOptions } from '../guardrails.types';
|
|
8
|
+
export interface GuardrailInterceptorOptions {
|
|
9
|
+
input?: GuardrailInputOptions;
|
|
10
|
+
output?: GuardrailOutputOptions;
|
|
11
|
+
checkOutput?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare class GuardrailInterceptor implements Interceptor {
|
|
14
|
+
private readonly guardrailsService;
|
|
15
|
+
constructor(guardrailsService: GuardrailsService);
|
|
16
|
+
intercept(context: RequestContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=guardrail.interceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail.interceptor.d.ts","sourceRoot":"","sources":["../../src/interceptors/guardrail.interceptor.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEzF,MAAM,WAAW,2BAA2B;IAC1C,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B,MAAM,CAAC,EAAE,sBAAsB,CAAC;IAChC,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,qBACa,oBAAqB,YAAW,WAAW;IAC1C,OAAO,CAAC,QAAQ,CAAC,iBAAiB;gBAAjB,iBAAiB,EAAE,iBAAiB;IAE3D,SAAS,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;CAiCzF"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* GuardrailInterceptor - Input/output guardrails for HTTP requests
|
|
4
|
+
*/
|
|
5
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
6
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
7
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
8
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
9
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
10
|
+
};
|
|
11
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
12
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.GuardrailInterceptor = void 0;
|
|
16
|
+
const core_1 = require("@hazeljs/core");
|
|
17
|
+
const guardrails_service_1 = require("../guardrails.service");
|
|
18
|
+
const guardrail_violation_error_1 = require("../errors/guardrail-violation.error");
|
|
19
|
+
let GuardrailInterceptor = class GuardrailInterceptor {
|
|
20
|
+
constructor(guardrailsService) {
|
|
21
|
+
this.guardrailsService = guardrailsService;
|
|
22
|
+
}
|
|
23
|
+
async intercept(context, next) {
|
|
24
|
+
if (context.body) {
|
|
25
|
+
const result = this.guardrailsService.checkInput(context.body, undefined);
|
|
26
|
+
if (!result.allowed) {
|
|
27
|
+
throw new guardrail_violation_error_1.GuardrailViolationError(result.blockedReason ?? 'Input blocked by guardrails', result.violations, result.blockedReason);
|
|
28
|
+
}
|
|
29
|
+
if (result.modified !== undefined) {
|
|
30
|
+
context.body = result.modified;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const response = await next();
|
|
34
|
+
if (response !== undefined && response !== null) {
|
|
35
|
+
const result = this.guardrailsService.checkOutput(response, undefined);
|
|
36
|
+
if (!result.allowed) {
|
|
37
|
+
throw new guardrail_violation_error_1.GuardrailViolationError(result.blockedReason ?? 'Output blocked by guardrails', result.violations, result.blockedReason);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return response;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
exports.GuardrailInterceptor = GuardrailInterceptor;
|
|
44
|
+
exports.GuardrailInterceptor = GuardrailInterceptor = __decorate([
|
|
45
|
+
(0, core_1.Injectable)(),
|
|
46
|
+
__metadata("design:paramtypes", [guardrails_service_1.GuardrailsService])
|
|
47
|
+
], GuardrailInterceptor);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GuardrailPipe - Input guardrails for HTTP request body/query
|
|
3
|
+
*/
|
|
4
|
+
import { PipeTransform } from '@hazeljs/core';
|
|
5
|
+
import type { RequestContext } from '@hazeljs/core';
|
|
6
|
+
import { GuardrailsService } from '../guardrails.service';
|
|
7
|
+
import type { GuardrailInputOptions } from '../guardrails.types';
|
|
8
|
+
export type GuardrailPipeOptions = GuardrailInputOptions;
|
|
9
|
+
export declare class GuardrailPipe implements PipeTransform {
|
|
10
|
+
private readonly guardrailsService;
|
|
11
|
+
constructor(guardrailsService: GuardrailsService);
|
|
12
|
+
transform<T>(value: T, _context: RequestContext): T | Promise<T>;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=guardrail.pipe.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail.pipe.d.ts","sourceRoot":"","sources":["../../src/pipes/guardrail.pipe.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAc,aAAa,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,MAAM,MAAM,oBAAoB,GAAG,qBAAqB,CAAC;AAEzD,qBACa,aAAc,YAAW,aAAa;IACrC,OAAO,CAAC,QAAQ,CAAC,iBAAiB;gBAAjB,iBAAiB,EAAE,iBAAiB;IAEjE,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAiBjE"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* GuardrailPipe - Input guardrails for HTTP request body/query
|
|
4
|
+
*/
|
|
5
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
6
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
7
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
8
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
9
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
10
|
+
};
|
|
11
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
12
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.GuardrailPipe = void 0;
|
|
16
|
+
const core_1 = require("@hazeljs/core");
|
|
17
|
+
const guardrails_service_1 = require("../guardrails.service");
|
|
18
|
+
const guardrail_violation_error_1 = require("../errors/guardrail-violation.error");
|
|
19
|
+
let GuardrailPipe = class GuardrailPipe {
|
|
20
|
+
constructor(guardrailsService) {
|
|
21
|
+
this.guardrailsService = guardrailsService;
|
|
22
|
+
}
|
|
23
|
+
transform(value, _context) {
|
|
24
|
+
const result = this.guardrailsService.checkInput(value);
|
|
25
|
+
if (!result.allowed) {
|
|
26
|
+
throw new guardrail_violation_error_1.GuardrailViolationError(result.blockedReason ?? 'Input blocked by guardrails', result.violations, result.blockedReason);
|
|
27
|
+
}
|
|
28
|
+
if (result.modified !== undefined) {
|
|
29
|
+
return result.modified;
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
exports.GuardrailPipe = GuardrailPipe;
|
|
35
|
+
exports.GuardrailPipe = GuardrailPipe = __decorate([
|
|
36
|
+
(0, core_1.Injectable)(),
|
|
37
|
+
__metadata("design:paramtypes", [guardrails_service_1.GuardrailsService])
|
|
38
|
+
], GuardrailPipe);
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hazeljs/guardrails",
|
|
3
|
+
"version": "0.2.0-beta.50",
|
|
4
|
+
"description": "Content safety, PII handling, and output validation for HazelJS AI applications",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc",
|
|
12
|
+
"test": "jest --coverage --passWithNoTests",
|
|
13
|
+
"lint": "eslint \"src/**/*.ts\"",
|
|
14
|
+
"lint:fix": "eslint \"src/**/*.ts\" --fix",
|
|
15
|
+
"clean": "rm -rf dist"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"reflect-metadata": "^0.2.1"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/jest": "^29.5.11",
|
|
22
|
+
"@types/node": "^20.17.50",
|
|
23
|
+
"@typescript-eslint/eslint-plugin": "^8.18.2",
|
|
24
|
+
"@typescript-eslint/parser": "^8.18.2",
|
|
25
|
+
"eslint": "^8.56.0",
|
|
26
|
+
"jest": "^29.7.0",
|
|
27
|
+
"ts-jest": "^29.1.2",
|
|
28
|
+
"typescript": "^5.3.3"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/hazel-js/hazeljs.git",
|
|
36
|
+
"directory": "packages/guardrails"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"hazeljs",
|
|
40
|
+
"guardrails",
|
|
41
|
+
"ai",
|
|
42
|
+
"pii",
|
|
43
|
+
"content-safety",
|
|
44
|
+
"prompt-injection",
|
|
45
|
+
"validation"
|
|
46
|
+
],
|
|
47
|
+
"author": "Muhammad Arslan <muhammad.arslan@hazeljs.com>",
|
|
48
|
+
"license": "Apache-2.0",
|
|
49
|
+
"bugs": {
|
|
50
|
+
"url": "https://github.com/hazeljs/hazel-js/issues"
|
|
51
|
+
},
|
|
52
|
+
"homepage": "https://hazeljs.com",
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"@hazeljs/core": ">=0.2.0-beta.0"
|
|
55
|
+
},
|
|
56
|
+
"gitHead": "aefca57a74856e3b0055ad65843e2a61681f6b99"
|
|
57
|
+
}
|