@deliverd/sdk 0.27.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.
@@ -0,0 +1,98 @@
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
+ export const PURVIEW_RESTRICTIONS = ["audit", "warn", "block"];
30
+ const RESTRICTION_RANK = { audit: 0, warn: 1, block: 2 };
31
+ /**
32
+ * The outcome of a `processContent` response body. Anything unrecognised in
33
+ * a policy action counts as a block: a DLP rule the code does not understand
34
+ * is not a reason to send the text.
35
+ */
36
+ export function purviewOutcomeFromResponse(body) {
37
+ const b = (body ?? {});
38
+ const actions = Array.isArray(b.policyActions) ? b.policyActions : [];
39
+ let restriction = null;
40
+ for (const raw of actions) {
41
+ const a = (raw ?? {});
42
+ const given = typeof a.restrictionAction === "string" ? a.restrictionAction : null;
43
+ const r = given === "audit" || given === "warn" || given === "block" ? given : "block";
44
+ if (restriction === null || RESTRICTION_RANK[r] > RESTRICTION_RANK[restriction])
45
+ restriction = r;
46
+ }
47
+ return { restriction, actions: actions.length, scopeModified: b.protectionScopeState === "modified", unavailable: false };
48
+ }
49
+ /** The outcome when Purview could not be reached, by the caller's choice. */
50
+ export function purviewUnavailable(onUnavailable) {
51
+ const restriction = onUnavailable === "deny" ? "block" : onUnavailable === "ask" ? "warn" : null;
52
+ return { restriction, actions: 0, scopeModified: false, unavailable: true };
53
+ }
54
+ const VERDICT_RANK = { allow: 0, redact: 1, ask: 2, deny: 3 };
55
+ /**
56
+ * Deliverd's verdict with Purview's held beside it: the stricter wins, and
57
+ * the reason says it was Purview. `enforce` false is the report-only mode,
58
+ * where Deliverd holds nothing back of its own but a Purview block still
59
+ * stands, because it is the organisation's own policy, not Deliverd's.
60
+ */
61
+ export function applyPurview(assessment, outcome, enforce = true) {
62
+ if (!outcome)
63
+ return assessment;
64
+ const reasons = [...assessment.reasons];
65
+ let verdict = assessment.verdict;
66
+ const raise = (to) => {
67
+ if (VERDICT_RANK[to] > VERDICT_RANK[verdict])
68
+ verdict = to;
69
+ };
70
+ if (outcome.unavailable) {
71
+ if (outcome.restriction === "block") {
72
+ raise("deny");
73
+ reasons.push("Microsoft Purview could not be reached, and this agent is set not to send text Purview has not checked.");
74
+ }
75
+ else if (outcome.restriction === "warn" && enforce) {
76
+ raise("ask");
77
+ reasons.push("Microsoft Purview could not be reached, so a person decides whether to send it unchecked.");
78
+ }
79
+ else {
80
+ reasons.push("Microsoft Purview could not be reached, so this was not checked against your Purview policies.");
81
+ }
82
+ return { ...assessment, verdict, reasons };
83
+ }
84
+ if (outcome.restriction === "block") {
85
+ raise("deny");
86
+ reasons.push("Your organisation's Microsoft Purview policy blocks sending this text.");
87
+ }
88
+ else if (outcome.restriction === "warn") {
89
+ if (enforce) {
90
+ raise("ask");
91
+ reasons.push("Your organisation's Microsoft Purview policy warns about this text, so a person decides.");
92
+ }
93
+ else {
94
+ reasons.push("Your organisation's Microsoft Purview policy warns about this text.");
95
+ }
96
+ }
97
+ return { ...assessment, verdict, reasons };
98
+ }
@@ -0,0 +1,114 @@
1
+ import { type PurviewOnUnavailable, type PurviewOutcome } from "./purview-rules.js";
2
+ export { type PurviewOutcome, type PurviewOnUnavailable, type PurviewRestriction } from "./purview-rules.js";
3
+ /**
4
+ * Ask your organisation's Microsoft Purview about a text before it goes to a
5
+ * model, and hold its answer beside Deliverd's.
6
+ *
7
+ * ```ts
8
+ * const purview = purviewCheck({
9
+ * token: () => credential.getToken("https://graph.microsoft.com/.default").then((t) => t.token),
10
+ * userId: entraObjectIdOfTheUser,
11
+ * app: { name: "Claims assistant", entraAppId: "11111111-…" },
12
+ * });
13
+ * const screened = await deliverd.screen(prompt, { aiSystemId: CLAIMS_MODEL, purview });
14
+ * ```
15
+ *
16
+ * The call goes from where your agent runs straight to Microsoft Graph
17
+ * (`processContent`), with your own Entra app's token, so the text goes to
18
+ * Microsoft and never to Deliverd. Deliverd is sent only the outcome: block,
19
+ * warn, audit or nothing. A block stops the text; a warn puts it to a person.
20
+ *
21
+ * The Entra app needs `Content.Process.User` or `Content.Process.All`
22
+ * (application permission with `userId`, or delegated with the signed-in
23
+ * user's token and no `userId`). Purview applies DLP policies to an
24
+ * Entra-registered app only when they were created with
25
+ * `New-DlpComplianceRule`; one made in the portal alone does not apply.
26
+ */
27
+ export interface PurviewCheckOptions {
28
+ /** A Microsoft Graph access token, or a function that returns one. Called on every check, so a credential can refresh it. */
29
+ token: string | (() => string | Promise<string>);
30
+ /** The Entra object id of the user the text is for. Omit to use `/me` with a delegated token. */
31
+ userId?: string;
32
+ /** Your app as Purview knows it: its name and its Entra application (client) id. */
33
+ app: {
34
+ name: string;
35
+ entraAppId: string;
36
+ version?: string;
37
+ };
38
+ /** The agent sending the text, when it is one, as Purview's AI agent info. */
39
+ agent?: {
40
+ id: string;
41
+ name: string;
42
+ version?: string;
43
+ blueprintId?: string;
44
+ };
45
+ /** One id per conversation, so Purview can group the texts in it. */
46
+ correlationId?: string;
47
+ /** What to do when Purview cannot be reached. Default `ask`: a person decides. */
48
+ onUnavailable?: PurviewOnUnavailable;
49
+ /** Milliseconds to wait for Purview. Default 10,000. */
50
+ timeoutMs?: number;
51
+ fetch?: typeof fetch;
52
+ }
53
+ /** A check `screen()` runs on the text before asking Deliverd. */
54
+ export type PurviewCheck = (text: string) => Promise<PurviewOutcome>;
55
+ /** The body `processContent` takes for a prompt about to be sent to a model. */
56
+ export declare function processContentBody(text: string, options: Pick<PurviewCheckOptions, "app" | "agent" | "correlationId">, sequenceNumber?: number): {
57
+ contentToProcess: {
58
+ contentEntries: {
59
+ agents?: {
60
+ blueprintId?: string | undefined;
61
+ version?: string | undefined;
62
+ "@odata.type": string;
63
+ identifier: string;
64
+ name: string;
65
+ }[] | undefined;
66
+ "@odata.type": string;
67
+ identifier: string;
68
+ content: {
69
+ "@odata.type": string;
70
+ data: string;
71
+ };
72
+ name: string;
73
+ correlationId: string;
74
+ sequenceNumber: number;
75
+ isTruncated: boolean;
76
+ createdDateTime: string;
77
+ modifiedDateTime: string;
78
+ }[];
79
+ activityMetadata: {
80
+ activity: string;
81
+ };
82
+ deviceMetadata: {};
83
+ protectedAppMetadata: {
84
+ name: string;
85
+ version: string;
86
+ applicationLocation: {
87
+ "@odata.type": string;
88
+ value: string;
89
+ };
90
+ };
91
+ integratedAppMetadata: {
92
+ name: string;
93
+ version: string;
94
+ };
95
+ };
96
+ };
97
+ export interface EntraAppTokenOptions {
98
+ /** The customer's Entra tenant id: where the DLP policies are. */
99
+ tenantId: string;
100
+ /** The app's application (client) id. */
101
+ clientId: string;
102
+ /** A client secret for it. Keep it in a secret store, never in code. */
103
+ clientSecret: string;
104
+ fetch?: typeof fetch;
105
+ }
106
+ /**
107
+ * A Microsoft Graph token for an app acting as itself (client credentials),
108
+ * for `purviewCheck`'s `token` where there is no signed-in user: a pipeline,
109
+ * a local MCP server, a back-end agent. Cached until five minutes before it
110
+ * expires. Use it with `userId`, the person the text is about or on behalf of.
111
+ */
112
+ export declare function entraAppToken(options: EntraAppTokenOptions): () => Promise<string>;
113
+ export declare function purviewCheck(options: PurviewCheckOptions): PurviewCheck;
114
+ //# sourceMappingURL=purview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"purview.d.ts","sourceRoot":"","sources":["../src/purview.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,oBAAoB,EACzB,KAAK,cAAc,EACpB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,oBAAoB,EAAE,KAAK,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7G;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,MAAM,WAAW,mBAAmB;IAClC,6HAA6H;IAC7H,KAAK,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACjD,iGAAiG;IACjG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oFAAoF;IACpF,GAAG,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC5D,8EAA8E;IAC9E,KAAK,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7E,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kFAAkF;IAClF,aAAa,CAAC,EAAE,oBAAoB,CAAC;IACrC,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,kEAAkE;AAClE,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;AAWrE,gFAAgF;AAChF,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,mBAAmB,EAAE,KAAK,GAAG,OAAO,GAAG,eAAe,CAAC,EAAE,cAAc,SAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwCzI;AAED,MAAM,WAAW,oBAAoB;IACnC,kEAAkE;IAClE,QAAQ,EAAE,MAAM,CAAC;IACjB,yCAAyC;IACzC,QAAQ,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,CAuBlF;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAiCvE"}
@@ -0,0 +1,124 @@
1
+ import { purviewOutcomeFromResponse, purviewUnavailable, } from "./purview-rules.js";
2
+ const GRAPH = "https://graph.microsoft.com/v1.0";
3
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+ function uuid() {
5
+ const c = globalThis.crypto;
6
+ if (c?.randomUUID)
7
+ return c.randomUUID();
8
+ return "xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx".replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
9
+ }
10
+ /** The body `processContent` takes for a prompt about to be sent to a model. */
11
+ export function processContentBody(text, options, sequenceNumber = 0) {
12
+ const now = new Date().toISOString();
13
+ return {
14
+ contentToProcess: {
15
+ contentEntries: [
16
+ {
17
+ "@odata.type": "microsoft.graph.processConversationMetadata",
18
+ identifier: uuid(),
19
+ content: { "@odata.type": "microsoft.graph.textContent", data: text },
20
+ name: `${options.app.name} prompt`,
21
+ correlationId: options.correlationId ?? uuid(),
22
+ sequenceNumber,
23
+ isTruncated: false,
24
+ createdDateTime: now,
25
+ modifiedDateTime: now,
26
+ ...(options.agent
27
+ ? {
28
+ agents: [
29
+ {
30
+ "@odata.type": "microsoft.graph.aiAgentInfo",
31
+ identifier: options.agent.id,
32
+ name: options.agent.name,
33
+ ...(options.agent.version ? { version: options.agent.version } : {}),
34
+ ...(options.agent.blueprintId ? { blueprintId: options.agent.blueprintId } : {}),
35
+ },
36
+ ],
37
+ }
38
+ : {}),
39
+ },
40
+ ],
41
+ activityMetadata: { activity: "uploadText" },
42
+ deviceMetadata: {},
43
+ protectedAppMetadata: {
44
+ name: options.app.name,
45
+ version: options.app.version ?? "1.0",
46
+ applicationLocation: { "@odata.type": "microsoft.graph.policyLocationApplication", value: options.app.entraAppId },
47
+ },
48
+ integratedAppMetadata: { name: options.app.name, version: options.app.version ?? "1.0" },
49
+ },
50
+ };
51
+ }
52
+ /**
53
+ * A Microsoft Graph token for an app acting as itself (client credentials),
54
+ * for `purviewCheck`'s `token` where there is no signed-in user: a pipeline,
55
+ * a local MCP server, a back-end agent. Cached until five minutes before it
56
+ * expires. Use it with `userId`, the person the text is about or on behalf of.
57
+ */
58
+ export function entraAppToken(options) {
59
+ if (!GUID.test(options.tenantId))
60
+ throw new Error("entraAppToken: tenantId is your Entra tenant id, a GUID.");
61
+ const doFetch = options.fetch ?? fetch;
62
+ let cached = null;
63
+ return async () => {
64
+ if (cached && Date.now() < cached.until)
65
+ return cached.token;
66
+ const res = await doFetch(`https://login.microsoftonline.com/${options.tenantId}/oauth2/v2.0/token`, {
67
+ method: "POST",
68
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
69
+ body: new URLSearchParams({
70
+ grant_type: "client_credentials",
71
+ client_id: options.clientId,
72
+ client_secret: options.clientSecret,
73
+ scope: "https://graph.microsoft.com/.default",
74
+ }).toString(),
75
+ signal: AbortSignal.timeout(10_000),
76
+ });
77
+ if (!res.ok)
78
+ throw new Error(`Entra refused the token request (${res.status}).`);
79
+ const body = (await res.json());
80
+ if (!body.access_token)
81
+ throw new Error("Entra returned no access token.");
82
+ cached = { token: body.access_token, until: Date.now() + Math.max(0, (body.expires_in ?? 3600) - 300) * 1000 };
83
+ return cached.token;
84
+ };
85
+ }
86
+ export function purviewCheck(options) {
87
+ if (!GUID.test(options.app.entraAppId))
88
+ throw new Error("purviewCheck: app.entraAppId is your Entra app's application (client) id, a GUID.");
89
+ if (options.userId !== undefined && !GUID.test(options.userId))
90
+ throw new Error("purviewCheck: userId is the user's Entra object id, a GUID.");
91
+ const doFetch = options.fetch ?? fetch;
92
+ const url = `${GRAPH}/${options.userId ? `users/${options.userId}` : "me"}/dataSecurityAndGovernance/processContent`;
93
+ const onUnavailable = options.onUnavailable ?? "ask";
94
+ let etag = null;
95
+ let sequence = 0;
96
+ return async (text) => {
97
+ try {
98
+ const token = typeof options.token === "function" ? await options.token() : options.token;
99
+ const res = await doFetch(url, {
100
+ method: "POST",
101
+ headers: {
102
+ Authorization: `Bearer ${token}`,
103
+ "Content-Type": "application/json",
104
+ ...(etag ? { "If-None-Match": etag } : {}),
105
+ },
106
+ body: JSON.stringify(processContentBody(text, options, sequence++)),
107
+ signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
108
+ });
109
+ if (res.status === 202 || res.status === 204)
110
+ return { restriction: null, actions: 0, scopeModified: false, unavailable: false };
111
+ if (!res.ok)
112
+ return purviewUnavailable(onUnavailable);
113
+ etag = res.headers.get("ETag") ?? etag;
114
+ const outcome = purviewOutcomeFromResponse(await res.json());
115
+ // Purview's policies changed: the next call starts from the new state.
116
+ if (outcome.scopeModified)
117
+ etag = res.headers.get("ETag");
118
+ return outcome;
119
+ }
120
+ catch {
121
+ return purviewUnavailable(onUnavailable);
122
+ }
123
+ };
124
+ }
@@ -43,7 +43,7 @@
43
43
  * **Add the version here when you publish it, not before.** An entry is a
44
44
  * claim that `npm install @deliverd/sdk@x` works today.
45
45
  */
46
- export declare const PUBLISHED_TO_NPM: readonly ["0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.6.2", "0.7.0", "0.7.1", "0.8.0", "0.8.1", "0.8.2", "0.9.0", "0.10.0", "0.11.0", "0.11.1", "0.12.0", "0.13.0", "0.14.0", "0.15.0", "0.16.0", "0.17.0", "0.18.0", "0.19.0", "0.20.0", "0.21.0", "0.22.0", "0.23.0", "0.24.0", "0.24.1", "0.25.0", "0.25.1", "0.26.0"];
46
+ export declare const PUBLISHED_TO_NPM: readonly ["0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.6.2", "0.7.0", "0.7.1", "0.8.0", "0.8.1", "0.8.2", "0.9.0", "0.10.0", "0.11.0", "0.11.1", "0.12.0", "0.13.0", "0.14.0", "0.15.0", "0.16.0", "0.17.0", "0.18.0", "0.19.0", "0.20.0", "0.21.0", "0.22.0", "0.23.0", "0.24.0", "0.24.1", "0.25.0", "0.25.1", "0.26.0", "0.27.0", "0.28.0"];
47
47
  /**
48
48
  * A fingerprint of what each *published* version recorded.
49
49
  *
@@ -1 +1 @@
1
- {"version":3,"file":"released.d.ts","sourceRoot":"","sources":["../src/released.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,gBAAgB,iVAmCnB,CAAC;AAEX;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAmGzC,CAAC;AAEF,eAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CA8iqBtD,CAAC"}
1
+ {"version":3,"file":"released.d.ts","sourceRoot":"","sources":["../src/released.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,gBAAgB,qWAqCnB,CAAC;AAEX;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAuGzC,CAAC;AAEF,eAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CA62vBtD,CAAC"}