@deliverd/sdk 0.28.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context.d.ts +7 -3
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +11 -3
- package/dist/data-screen.d.ts.map +1 -1
- package/dist/data-screen.js +33 -2
- package/dist/dev.d.ts.map +1 -1
- package/dist/dev.js +4 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/purview-rules.d.ts +63 -0
- package/dist/purview-rules.d.ts.map +1 -0
- package/dist/purview-rules.js +98 -0
- package/dist/purview.d.ts +114 -0
- package/dist/purview.d.ts.map +1 -0
- package/dist/purview.js +124 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +1458 -0
- package/dist/screen.d.ts +8 -0
- package/dist/screen.d.ts.map +1 -1
- package/dist/screen.js +2 -0
- package/dist/types.d.ts +72 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/context.ts +15 -3
- package/src/data-screen.ts +33 -2
- package/src/dev.ts +4 -2
- package/src/index.ts +1 -0
- package/src/purview-rules.ts +117 -0
- package/src/purview.ts +182 -0
- package/src/released.ts +1459 -0
- package/src/screen.ts +10 -0
- package/src/types.ts +72 -2
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Microsoft Purview's answer on a text, held beside Deliverd's own.
|
|
3
|
+
*
|
|
4
|
+
* An organisation that runs Microsoft Purview has already written its data
|
|
5
|
+
* loss prevention (DLP) policies there. An app can ask Purview about a text
|
|
6
|
+
* before it is sent to a model, through Microsoft Graph's `processContent`,
|
|
7
|
+
* and Purview answers with what the app must do: nothing, or a restricted
|
|
8
|
+
* access action whose `restrictionAction` is `audit`, `warn` or `block`.
|
|
9
|
+
*
|
|
10
|
+
* The SDKs make that call where the agent runs, with the organisation's own
|
|
11
|
+
* Entra app, so the text goes to Microsoft and never to Deliverd. Deliverd is
|
|
12
|
+
* sent only the outcome below, and holds it beside its own screening:
|
|
13
|
+
*
|
|
14
|
+
* - `block`: nothing is sent. The organisation's own policy said so, and it
|
|
15
|
+
* is honoured on every plan, report-only included.
|
|
16
|
+
* - `warn`: a person decides, through an ordinary approval. Purview's "warn"
|
|
17
|
+
* is an override a user may make; here the override is recorded, with who
|
|
18
|
+
* made it.
|
|
19
|
+
* - `audit`: no hold. Purview has recorded the activity itself.
|
|
20
|
+
*
|
|
21
|
+
* When Purview cannot be reached, the caller has already decided what that
|
|
22
|
+
* means (allow, ask or deny) and says so in `restriction`, with `unavailable`
|
|
23
|
+
* set, so the reason given is honest about it.
|
|
24
|
+
*
|
|
25
|
+
* Pure, with no imports. This file is copied verbatim into
|
|
26
|
+
* `packages/sdk/src/purview-rules.ts` and `packages/screen/src/purview-rules.ts`,
|
|
27
|
+
* and a test fails when they differ.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
export const PURVIEW_RESTRICTIONS = ["audit", "warn", "block"] as const;
|
|
31
|
+
export type PurviewRestriction = (typeof PURVIEW_RESTRICTIONS)[number];
|
|
32
|
+
|
|
33
|
+
export interface PurviewOutcome {
|
|
34
|
+
/** The strictest restriction among Purview's policy actions; null when there were none. */
|
|
35
|
+
restriction: PurviewRestriction | null;
|
|
36
|
+
/** How many policy actions Purview returned. */
|
|
37
|
+
actions: number;
|
|
38
|
+
/** Purview said the organisation's policies changed since the caller last looked. */
|
|
39
|
+
scopeModified: boolean;
|
|
40
|
+
/** Purview could not be reached; `restriction` is what the caller chose for that case. */
|
|
41
|
+
unavailable: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** What a caller does when Purview cannot be reached. */
|
|
45
|
+
export type PurviewOnUnavailable = "allow" | "ask" | "deny";
|
|
46
|
+
|
|
47
|
+
const RESTRICTION_RANK: Record<PurviewRestriction, number> = { audit: 0, warn: 1, block: 2 };
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The outcome of a `processContent` response body. Anything unrecognised in
|
|
51
|
+
* a policy action counts as a block: a DLP rule the code does not understand
|
|
52
|
+
* is not a reason to send the text.
|
|
53
|
+
*/
|
|
54
|
+
export function purviewOutcomeFromResponse(body: unknown): PurviewOutcome {
|
|
55
|
+
const b = (body ?? {}) as { policyActions?: unknown; protectionScopeState?: unknown };
|
|
56
|
+
const actions = Array.isArray(b.policyActions) ? b.policyActions : [];
|
|
57
|
+
let restriction: PurviewRestriction | null = null;
|
|
58
|
+
for (const raw of actions) {
|
|
59
|
+
const a = (raw ?? {}) as { action?: unknown; restrictionAction?: unknown };
|
|
60
|
+
const given = typeof a.restrictionAction === "string" ? a.restrictionAction : null;
|
|
61
|
+
const r: PurviewRestriction = given === "audit" || given === "warn" || given === "block" ? given : "block";
|
|
62
|
+
if (restriction === null || RESTRICTION_RANK[r] > RESTRICTION_RANK[restriction]) restriction = r;
|
|
63
|
+
}
|
|
64
|
+
return { restriction, actions: actions.length, scopeModified: b.protectionScopeState === "modified", unavailable: false };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The outcome when Purview could not be reached, by the caller's choice. */
|
|
68
|
+
export function purviewUnavailable(onUnavailable: PurviewOnUnavailable): PurviewOutcome {
|
|
69
|
+
const restriction: PurviewRestriction | null = onUnavailable === "deny" ? "block" : onUnavailable === "ask" ? "warn" : null;
|
|
70
|
+
return { restriction, actions: 0, scopeModified: false, unavailable: true };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type Verdict = "allow" | "redact" | "ask" | "deny";
|
|
74
|
+
const VERDICT_RANK: Record<Verdict, number> = { allow: 0, redact: 1, ask: 2, deny: 3 };
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Deliverd's verdict with Purview's held beside it: the stricter wins, and
|
|
78
|
+
* the reason says it was Purview. `enforce` false is the report-only mode,
|
|
79
|
+
* where Deliverd holds nothing back of its own but a Purview block still
|
|
80
|
+
* stands, because it is the organisation's own policy, not Deliverd's.
|
|
81
|
+
*/
|
|
82
|
+
export function applyPurview<T extends { verdict: Verdict; reasons: string[] }>(
|
|
83
|
+
assessment: T,
|
|
84
|
+
outcome: PurviewOutcome | null | undefined,
|
|
85
|
+
enforce = true
|
|
86
|
+
): T {
|
|
87
|
+
if (!outcome) return assessment;
|
|
88
|
+
const reasons = [...assessment.reasons];
|
|
89
|
+
let verdict = assessment.verdict;
|
|
90
|
+
const raise = (to: Verdict) => {
|
|
91
|
+
if (VERDICT_RANK[to] > VERDICT_RANK[verdict]) verdict = to;
|
|
92
|
+
};
|
|
93
|
+
if (outcome.unavailable) {
|
|
94
|
+
if (outcome.restriction === "block") {
|
|
95
|
+
raise("deny");
|
|
96
|
+
reasons.push("Microsoft Purview could not be reached, and this agent is set not to send text Purview has not checked.");
|
|
97
|
+
} else if (outcome.restriction === "warn" && enforce) {
|
|
98
|
+
raise("ask");
|
|
99
|
+
reasons.push("Microsoft Purview could not be reached, so a person decides whether to send it unchecked.");
|
|
100
|
+
} else {
|
|
101
|
+
reasons.push("Microsoft Purview could not be reached, so this was not checked against your Purview policies.");
|
|
102
|
+
}
|
|
103
|
+
return { ...assessment, verdict, reasons };
|
|
104
|
+
}
|
|
105
|
+
if (outcome.restriction === "block") {
|
|
106
|
+
raise("deny");
|
|
107
|
+
reasons.push("Your organisation's Microsoft Purview policy blocks sending this text.");
|
|
108
|
+
} else if (outcome.restriction === "warn") {
|
|
109
|
+
if (enforce) {
|
|
110
|
+
raise("ask");
|
|
111
|
+
reasons.push("Your organisation's Microsoft Purview policy warns about this text, so a person decides.");
|
|
112
|
+
} else {
|
|
113
|
+
reasons.push("Your organisation's Microsoft Purview policy warns about this text.");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { ...assessment, verdict, reasons };
|
|
117
|
+
}
|
package/src/purview.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import {
|
|
2
|
+
purviewOutcomeFromResponse,
|
|
3
|
+
purviewUnavailable,
|
|
4
|
+
type PurviewOnUnavailable,
|
|
5
|
+
type PurviewOutcome,
|
|
6
|
+
} from "./purview-rules.js";
|
|
7
|
+
|
|
8
|
+
export { type PurviewOutcome, type PurviewOnUnavailable, type PurviewRestriction } from "./purview-rules.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Ask your organisation's Microsoft Purview about a text before it goes to a
|
|
12
|
+
* model, and hold its answer beside Deliverd's.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* const purview = purviewCheck({
|
|
16
|
+
* token: () => credential.getToken("https://graph.microsoft.com/.default").then((t) => t.token),
|
|
17
|
+
* userId: entraObjectIdOfTheUser,
|
|
18
|
+
* app: { name: "Claims assistant", entraAppId: "11111111-…" },
|
|
19
|
+
* });
|
|
20
|
+
* const screened = await deliverd.screen(prompt, { aiSystemId: CLAIMS_MODEL, purview });
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* The call goes from where your agent runs straight to Microsoft Graph
|
|
24
|
+
* (`processContent`), with your own Entra app's token, so the text goes to
|
|
25
|
+
* Microsoft and never to Deliverd. Deliverd is sent only the outcome: block,
|
|
26
|
+
* warn, audit or nothing. A block stops the text; a warn puts it to a person.
|
|
27
|
+
*
|
|
28
|
+
* The Entra app needs `Content.Process.User` or `Content.Process.All`
|
|
29
|
+
* (application permission with `userId`, or delegated with the signed-in
|
|
30
|
+
* user's token and no `userId`). Purview applies DLP policies to an
|
|
31
|
+
* Entra-registered app only when they were created with
|
|
32
|
+
* `New-DlpComplianceRule`; one made in the portal alone does not apply.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
export interface PurviewCheckOptions {
|
|
36
|
+
/** A Microsoft Graph access token, or a function that returns one. Called on every check, so a credential can refresh it. */
|
|
37
|
+
token: string | (() => string | Promise<string>);
|
|
38
|
+
/** The Entra object id of the user the text is for. Omit to use `/me` with a delegated token. */
|
|
39
|
+
userId?: string;
|
|
40
|
+
/** Your app as Purview knows it: its name and its Entra application (client) id. */
|
|
41
|
+
app: { name: string; entraAppId: string; version?: string };
|
|
42
|
+
/** The agent sending the text, when it is one, as Purview's AI agent info. */
|
|
43
|
+
agent?: { id: string; name: string; version?: string; blueprintId?: string };
|
|
44
|
+
/** One id per conversation, so Purview can group the texts in it. */
|
|
45
|
+
correlationId?: string;
|
|
46
|
+
/** What to do when Purview cannot be reached. Default `ask`: a person decides. */
|
|
47
|
+
onUnavailable?: PurviewOnUnavailable;
|
|
48
|
+
/** Milliseconds to wait for Purview. Default 10,000. */
|
|
49
|
+
timeoutMs?: number;
|
|
50
|
+
fetch?: typeof fetch;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A check `screen()` runs on the text before asking Deliverd. */
|
|
54
|
+
export type PurviewCheck = (text: string) => Promise<PurviewOutcome>;
|
|
55
|
+
|
|
56
|
+
const GRAPH = "https://graph.microsoft.com/v1.0";
|
|
57
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
58
|
+
|
|
59
|
+
function uuid(): string {
|
|
60
|
+
const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
|
61
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
62
|
+
return "xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx".replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The body `processContent` takes for a prompt about to be sent to a model. */
|
|
66
|
+
export function processContentBody(text: string, options: Pick<PurviewCheckOptions, "app" | "agent" | "correlationId">, sequenceNumber = 0) {
|
|
67
|
+
const now = new Date().toISOString();
|
|
68
|
+
return {
|
|
69
|
+
contentToProcess: {
|
|
70
|
+
contentEntries: [
|
|
71
|
+
{
|
|
72
|
+
"@odata.type": "microsoft.graph.processConversationMetadata",
|
|
73
|
+
identifier: uuid(),
|
|
74
|
+
content: { "@odata.type": "microsoft.graph.textContent", data: text },
|
|
75
|
+
name: `${options.app.name} prompt`,
|
|
76
|
+
correlationId: options.correlationId ?? uuid(),
|
|
77
|
+
sequenceNumber,
|
|
78
|
+
isTruncated: false,
|
|
79
|
+
createdDateTime: now,
|
|
80
|
+
modifiedDateTime: now,
|
|
81
|
+
...(options.agent
|
|
82
|
+
? {
|
|
83
|
+
agents: [
|
|
84
|
+
{
|
|
85
|
+
"@odata.type": "microsoft.graph.aiAgentInfo",
|
|
86
|
+
identifier: options.agent.id,
|
|
87
|
+
name: options.agent.name,
|
|
88
|
+
...(options.agent.version ? { version: options.agent.version } : {}),
|
|
89
|
+
...(options.agent.blueprintId ? { blueprintId: options.agent.blueprintId } : {}),
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
}
|
|
93
|
+
: {}),
|
|
94
|
+
},
|
|
95
|
+
],
|
|
96
|
+
activityMetadata: { activity: "uploadText" },
|
|
97
|
+
deviceMetadata: {},
|
|
98
|
+
protectedAppMetadata: {
|
|
99
|
+
name: options.app.name,
|
|
100
|
+
version: options.app.version ?? "1.0",
|
|
101
|
+
applicationLocation: { "@odata.type": "microsoft.graph.policyLocationApplication", value: options.app.entraAppId },
|
|
102
|
+
},
|
|
103
|
+
integratedAppMetadata: { name: options.app.name, version: options.app.version ?? "1.0" },
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface EntraAppTokenOptions {
|
|
109
|
+
/** The customer's Entra tenant id: where the DLP policies are. */
|
|
110
|
+
tenantId: string;
|
|
111
|
+
/** The app's application (client) id. */
|
|
112
|
+
clientId: string;
|
|
113
|
+
/** A client secret for it. Keep it in a secret store, never in code. */
|
|
114
|
+
clientSecret: string;
|
|
115
|
+
fetch?: typeof fetch;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A Microsoft Graph token for an app acting as itself (client credentials),
|
|
120
|
+
* for `purviewCheck`'s `token` where there is no signed-in user: a pipeline,
|
|
121
|
+
* a local MCP server, a back-end agent. Cached until five minutes before it
|
|
122
|
+
* expires. Use it with `userId`, the person the text is about or on behalf of.
|
|
123
|
+
*/
|
|
124
|
+
export function entraAppToken(options: EntraAppTokenOptions): () => Promise<string> {
|
|
125
|
+
if (!GUID.test(options.tenantId)) throw new Error("entraAppToken: tenantId is your Entra tenant id, a GUID.");
|
|
126
|
+
const doFetch = options.fetch ?? fetch;
|
|
127
|
+
let cached: { token: string; until: number } | null = null;
|
|
128
|
+
return async () => {
|
|
129
|
+
if (cached && Date.now() < cached.until) return cached.token;
|
|
130
|
+
const res = await doFetch(`https://login.microsoftonline.com/${options.tenantId}/oauth2/v2.0/token`, {
|
|
131
|
+
method: "POST",
|
|
132
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
133
|
+
body: new URLSearchParams({
|
|
134
|
+
grant_type: "client_credentials",
|
|
135
|
+
client_id: options.clientId,
|
|
136
|
+
client_secret: options.clientSecret,
|
|
137
|
+
scope: "https://graph.microsoft.com/.default",
|
|
138
|
+
}).toString(),
|
|
139
|
+
signal: AbortSignal.timeout(10_000),
|
|
140
|
+
});
|
|
141
|
+
if (!res.ok) throw new Error(`Entra refused the token request (${res.status}).`);
|
|
142
|
+
const body = (await res.json()) as { access_token?: string; expires_in?: number };
|
|
143
|
+
if (!body.access_token) throw new Error("Entra returned no access token.");
|
|
144
|
+
cached = { token: body.access_token, until: Date.now() + Math.max(0, (body.expires_in ?? 3600) - 300) * 1000 };
|
|
145
|
+
return cached.token;
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function purviewCheck(options: PurviewCheckOptions): PurviewCheck {
|
|
150
|
+
if (!GUID.test(options.app.entraAppId)) throw new Error("purviewCheck: app.entraAppId is your Entra app's application (client) id, a GUID.");
|
|
151
|
+
if (options.userId !== undefined && !GUID.test(options.userId)) throw new Error("purviewCheck: userId is the user's Entra object id, a GUID.");
|
|
152
|
+
const doFetch = options.fetch ?? fetch;
|
|
153
|
+
const url = `${GRAPH}/${options.userId ? `users/${options.userId}` : "me"}/dataSecurityAndGovernance/processContent`;
|
|
154
|
+
const onUnavailable = options.onUnavailable ?? "ask";
|
|
155
|
+
let etag: string | null = null;
|
|
156
|
+
let sequence = 0;
|
|
157
|
+
|
|
158
|
+
return async (text: string) => {
|
|
159
|
+
try {
|
|
160
|
+
const token = typeof options.token === "function" ? await options.token() : options.token;
|
|
161
|
+
const res = await doFetch(url, {
|
|
162
|
+
method: "POST",
|
|
163
|
+
headers: {
|
|
164
|
+
Authorization: `Bearer ${token}`,
|
|
165
|
+
"Content-Type": "application/json",
|
|
166
|
+
...(etag ? { "If-None-Match": etag } : {}),
|
|
167
|
+
},
|
|
168
|
+
body: JSON.stringify(processContentBody(text, options, sequence++)),
|
|
169
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
|
|
170
|
+
});
|
|
171
|
+
if (res.status === 202 || res.status === 204) return { restriction: null, actions: 0, scopeModified: false, unavailable: false };
|
|
172
|
+
if (!res.ok) return purviewUnavailable(onUnavailable);
|
|
173
|
+
etag = res.headers.get("ETag") ?? etag;
|
|
174
|
+
const outcome = purviewOutcomeFromResponse(await res.json());
|
|
175
|
+
// Purview's policies changed: the next call starts from the new state.
|
|
176
|
+
if (outcome.scopeModified) etag = res.headers.get("ETag");
|
|
177
|
+
return outcome;
|
|
178
|
+
} catch {
|
|
179
|
+
return purviewUnavailable(onUnavailable);
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|