@alfe.ai/openclaw-identity 0.0.11 → 0.0.13

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,420 @@
1
+ let _alfe_ai_config = require("@alfe.ai/config");
2
+ let _alfe_ai_agent_api_client = require("@alfe.ai/agent-api-client");
3
+ let _sinclair_typebox = require("@sinclair/typebox");
4
+ let node_module = require("node:module");
5
+ let _auriclabs_roles = require("@auriclabs/roles");
6
+ //#region src/agent-exec-gate.ts
7
+ /**
8
+ * Phase 1 Stage E — `agent:exec` gate evaluation.
9
+ *
10
+ * Round 6 strict-namespacing gate context (`{tool, args}`): the gate
11
+ * passes the tool name as a sift CONTEXT field, not as the action.
12
+ * Permissions narrow which tools an identity may exec via sift
13
+ * conditions on the `tool` field. `args` is its own field — never
14
+ * spread — so a tool whose args legitimately include a `tool` key
15
+ * can't override the gate's value (closes the round-5 toolArgs.tool
16
+ * collision).
17
+ *
18
+ * The function is a thin wrapper around `createAbility(...).has(...)`
19
+ * that asserts the architecture-invariant "exactly one ability.has
20
+ * call per gate" rule from the verify-roles-architecture script. Any
21
+ * caller that loops over multiple scopes and OR-aggregates the result
22
+ * silently loses `cannot` semantics — the wrapper makes the contract
23
+ * explicit and testable.
24
+ *
25
+ * Today this function is wired into `before_tool_call` only for the
26
+ * TOKEN path (B.0.7 atomic flip carries the token's `Permission[]` in
27
+ * `ctx.tokenPermissions`). The JWT path still falls back to permissive
28
+ * because the agent runtime can't yet fetch the resolved permission
29
+ * set for `ctx.actingIdentityId` (needs an AgentApiClient endpoint
30
+ * that doesn't exist yet — landing alongside Stage D's full rollout).
31
+ */
32
+ /**
33
+ * Evaluate the round-6 strict-namespacing gate. Single
34
+ * `ability.has({...}, {tool, args})` call per invocation — never
35
+ * fan out across multiple permission shapes.
36
+ *
37
+ * `permissions` is whatever the caller already has on hand (a token's
38
+ * `Permission[]`, a session-cached resolved set, etc.). The function
39
+ * doesn't fetch, doesn't cache, doesn't memoize — those concerns live
40
+ * one layer up.
41
+ */
42
+ function evaluateAgentExec(permissions, args) {
43
+ if (!args.agentId) return { allowed: false };
44
+ const ability = (0, _auriclabs_roles.createAbility)(permissions);
45
+ const gatePermission = {
46
+ subject: "agent",
47
+ action: "exec",
48
+ scope: `agent:${args.agentId}`
49
+ };
50
+ return { allowed: ability.has(gatePermission, {
51
+ tool: args.toolName,
52
+ args: args.toolArgs
53
+ }) };
54
+ }
55
+ /**
56
+ * Translate the gate decision into the before_tool_call hook's return
57
+ * shape. `undefined` means "no opinion — allow"; `{ block: true, ... }`
58
+ * means deny.
59
+ *
60
+ * - `allowed === true` → undefined (allow regardless of mode).
61
+ * - `allowed === false` + mode === "fail-closed" → block.
62
+ * - `allowed === false` + mode === "fail-open" → undefined (warn-only;
63
+ * caller should log the would-deny but let it through). Returning
64
+ * undefined here is what makes the rollout safe — Stage H flips the
65
+ * env to fail-closed once the deny-rate metric stabilizes.
66
+ */
67
+ function applyGateMode(decision, mode, toolName) {
68
+ if (decision.allowed) return void 0;
69
+ if (mode === "fail-open") return void 0;
70
+ return {
71
+ block: true,
72
+ blockReason: `Permissions: tool '${toolName}' not allowed for this identity`
73
+ };
74
+ }
75
+ /**
76
+ * Resolve the kill-switch from process.env. Defaults to "fail-closed"
77
+ * in production and "fail-open" elsewhere — Stage H flips production
78
+ * to fail-closed once metrics confirm a stable deny rate.
79
+ */
80
+ function resolveToolGatingMode() {
81
+ const raw = process.env.OPENCLAW_TOOL_GATING;
82
+ if (raw === "fail-open" || raw === "fail-closed") return raw;
83
+ return "fail-open";
84
+ }
85
+ //#endregion
86
+ //#region src/plugin.ts
87
+ /**
88
+ * @alfe.ai/openclaw-identity — OpenClaw native plugin
89
+ *
90
+ * HTTP-based identity resolution + AccessConfig admission gate. Installed as
91
+ * part of the core alfe integration on every agent.
92
+ *
93
+ * Hooks:
94
+ * - message_received → always resolves the sender, gates on accessAllowed,
95
+ * blocks unknown senders (read-only resolve).
96
+ * - before_tool_call → typed `(event: ToolCallEvent, ctx: ToolCallContext)`
97
+ * hook (Phase 1 Stage A.0). Today: permissive no-op
98
+ * stub. Phase 1 Stage E swaps the stub for the
99
+ * `agent:exec` + sift gate (Decision 17).
100
+ *
101
+ * `after_tool_call` is intentionally absent — tool-call audit lives in a
102
+ * future dedicated audit service, not in identity.
103
+ */
104
+ const pkg = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("../package.json");
105
+ const RESOLVE_CACHE_TTL_MS = 6e4;
106
+ const resolveCache = /* @__PURE__ */ new Map();
107
+ function getCachedResolve(key) {
108
+ const entry = resolveCache.get(key);
109
+ if (!entry) return null;
110
+ if (Date.now() > entry.expiresAt) {
111
+ resolveCache.delete(key);
112
+ return null;
113
+ }
114
+ return entry;
115
+ }
116
+ function setCachedResolve(key, value) {
117
+ resolveCache.set(key, {
118
+ ...value,
119
+ expiresAt: Date.now() + RESOLVE_CACHE_TTL_MS
120
+ });
121
+ }
122
+ function ok(data) {
123
+ return {
124
+ content: [{
125
+ type: "text",
126
+ text: JSON.stringify(data)
127
+ }],
128
+ details: data
129
+ };
130
+ }
131
+ function errResult(message) {
132
+ return {
133
+ content: [{
134
+ type: "text",
135
+ text: JSON.stringify({ error: message })
136
+ }],
137
+ details: { error: message }
138
+ };
139
+ }
140
+ function defineTool(def) {
141
+ return {
142
+ name: def.name,
143
+ description: def.description,
144
+ label: def.name,
145
+ parameters: def.parameters,
146
+ execute: async (_toolCallId, params) => {
147
+ try {
148
+ return ok(await def.handler(params));
149
+ } catch (e) {
150
+ return errResult(e.message);
151
+ }
152
+ }
153
+ };
154
+ }
155
+ const plugin = {
156
+ id: "@alfe.ai/openclaw-identity",
157
+ name: "Alfe Identity",
158
+ description: "Identity resolution and access gating for inbound messages",
159
+ version: pkg.version,
160
+ activate(api) {
161
+ const log = api.logger;
162
+ log.info("Alfe Identity plugin activating...");
163
+ let client;
164
+ try {
165
+ const config = (0, _alfe_ai_config.resolveConfig)();
166
+ client = new _alfe_ai_agent_api_client.AgentApiClient({
167
+ apiKey: config.apiKey,
168
+ apiUrl: config.apiUrl
169
+ });
170
+ } catch (err) {
171
+ log.error(`Identity plugin: failed to resolve config — ${err instanceof Error ? err.message : String(err)}`);
172
+ return;
173
+ }
174
+ const tools = [
175
+ defineTool({
176
+ name: "who_is_this",
177
+ description: "Look up an identity by provider + platformId — returns full identity context (profile, contacts, platforms, notes, tags, recent changelog). Returns `{found:false}` for unknown senders. This tool DOES NOT create new identities.",
178
+ parameters: _sinclair_typebox.Type.Object({
179
+ provider: _sinclair_typebox.Type.String({ description: "Provider name (discord, slack, chat, google-chat, clerk, etc.)" }),
180
+ platformId: _sinclair_typebox.Type.String({ description: "Provider-specific user identifier" })
181
+ }),
182
+ handler: async (params) => {
183
+ const result = await client.resolveIdentity({
184
+ provider: params.provider,
185
+ platformId: params.platformId
186
+ });
187
+ if (!result.identityId) return { found: false };
188
+ return client.getIdentityContext(result.identityId);
189
+ }
190
+ }),
191
+ defineTool({
192
+ name: "lookup_identity",
193
+ description: "Search identities by name. Returns multiple matches.",
194
+ parameters: _sinclair_typebox.Type.Object({
195
+ query: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "Text search query" })),
196
+ status: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String())
197
+ }),
198
+ handler: (params) => client.searchIdentities({
199
+ q: params.query,
200
+ status: params.status
201
+ })
202
+ }),
203
+ defineTool({
204
+ name: "merge_identities",
205
+ description: "Merge two identity records — transfers contacts, platforms, notes, tags, aliases to the survivor. Hard-move, transactional.",
206
+ parameters: _sinclair_typebox.Type.Object({
207
+ survivorId: _sinclair_typebox.Type.String({ description: "Identity to keep" }),
208
+ mergedId: _sinclair_typebox.Type.String({ description: "Identity to merge into survivor" })
209
+ }),
210
+ handler: (params) => client.mergeIdentities(params.survivorId, {
211
+ mergedId: params.mergedId,
212
+ changedBy: {
213
+ type: "agent",
214
+ id: "plugin"
215
+ }
216
+ })
217
+ }),
218
+ defineTool({
219
+ name: "unmerge_identities",
220
+ description: "Reverse a merge — restore previously merged identity.",
221
+ parameters: _sinclair_typebox.Type.Object({ mergedId: _sinclair_typebox.Type.String({ description: "Identity that was merged (has mergedInto pointer)" }) }),
222
+ handler: (params) => client.unmergeIdentity(params.mergedId, { changedBy: {
223
+ type: "agent",
224
+ id: "plugin"
225
+ } })
226
+ }),
227
+ defineTool({
228
+ name: "add_identity_note",
229
+ description: "Add an observation or note about an identity. Use category 'context' for unverified affiliation claims (self-reported title/company) — those do NOT belong on the identity row directly.",
230
+ parameters: _sinclair_typebox.Type.Object({
231
+ identityId: _sinclair_typebox.Type.String(),
232
+ content: _sinclair_typebox.Type.String(),
233
+ category: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "observation, preference, relationship, context, or warning" }))
234
+ }),
235
+ handler: (params) => client.addIdentityNote(params.identityId, {
236
+ content: params.content,
237
+ category: params.category,
238
+ changedBy: {
239
+ type: "agent",
240
+ id: "plugin"
241
+ }
242
+ })
243
+ }),
244
+ defineTool({
245
+ name: "tag_identity",
246
+ description: "Add or remove a tag on an identity.",
247
+ parameters: _sinclair_typebox.Type.Object({
248
+ identityId: _sinclair_typebox.Type.String(),
249
+ tag: _sinclair_typebox.Type.String(),
250
+ action: _sinclair_typebox.Type.String({ description: "'add' or 'remove'" })
251
+ }),
252
+ handler: (params) => client.tagIdentity(params.identityId, {
253
+ tag: params.tag,
254
+ action: params.action,
255
+ changedBy: {
256
+ type: "agent",
257
+ id: "plugin"
258
+ }
259
+ })
260
+ }),
261
+ defineTool({
262
+ name: "get_identity_changelog",
263
+ description: "Get the changelog for an identity — versions, diffs, who changed what.",
264
+ parameters: _sinclair_typebox.Type.Object({
265
+ identityId: _sinclair_typebox.Type.String(),
266
+ limit: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.Number())
267
+ }),
268
+ handler: (params) => client.getIdentityChangelog(params.identityId, { limit: params.limit })
269
+ }),
270
+ defineTool({
271
+ name: "rollback_identity",
272
+ description: "Revert an identity to a previous version.",
273
+ parameters: _sinclair_typebox.Type.Object({
274
+ identityId: _sinclair_typebox.Type.String(),
275
+ targetVersion: _sinclair_typebox.Type.Number()
276
+ }),
277
+ handler: (params) => client.rollbackIdentity(params.identityId, {
278
+ targetVersion: params.targetVersion,
279
+ changedBy: {
280
+ type: "agent",
281
+ id: "plugin"
282
+ }
283
+ })
284
+ }),
285
+ defineTool({
286
+ name: "update_identity",
287
+ description: "Update display-shape fields on an identity: name / avatarUrl / timezone / locale. Contact mutations go through the verify flow — this tool will NOT accept email or mobile. Title and company live on org membership rows, not here.",
288
+ parameters: _sinclair_typebox.Type.Object({
289
+ identityId: _sinclair_typebox.Type.String(),
290
+ name: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String()),
291
+ avatarUrl: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String()),
292
+ timezone: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String()),
293
+ locale: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String())
294
+ }),
295
+ handler: (params) => {
296
+ const { identityId, ...rest } = params;
297
+ return client.updateIdentity(identityId, rest);
298
+ }
299
+ }),
300
+ defineTool({
301
+ name: "request_identity_verification",
302
+ description: "Send a verification phrase to verify the user controls an email or mobile endpoint. Use this when the user has just told you their email or mobile number and you want them to confirm it. Pass exactly one of `contactEmail` or `contactMobile`. The person must relay the phrase back via `confirm_identity_verification`.",
303
+ parameters: _sinclair_typebox.Type.Object({
304
+ claimedIdentityId: _sinclair_typebox.Type.String({ description: "Identity being claimed" }),
305
+ requestingIdentityId: _sinclair_typebox.Type.String({ description: "Identity of the person making the claim" }),
306
+ requestingProvider: _sinclair_typebox.Type.String({ description: "Provider the requester is on (discord, slack, chat, etc.)" }),
307
+ requestingPlatformId: _sinclair_typebox.Type.String({ description: "Requester's provider-specific user ID" }),
308
+ contactEmail: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "Email to verify (mutually exclusive with contactMobile)" })),
309
+ contactMobile: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "E.164 mobile to verify (mutually exclusive with contactEmail)" })),
310
+ preferredChannel: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "When neither contactEmail nor contactMobile is provided, pick which existing verified contact to deliver to: 'mobile' or 'email'" }))
311
+ }),
312
+ handler: (params) => {
313
+ const contactEmail = params.contactEmail;
314
+ const contactMobile = params.contactMobile;
315
+ if (contactEmail && contactMobile) return Promise.resolve({ error: "Specify exactly one of contactEmail or contactMobile, not both" });
316
+ const contact = contactEmail ? {
317
+ channel: "email",
318
+ value: contactEmail
319
+ } : contactMobile ? {
320
+ channel: "mobile",
321
+ value: contactMobile
322
+ } : void 0;
323
+ return client.requestIdentityVerification({
324
+ claimedIdentityId: params.claimedIdentityId,
325
+ requestingIdentityId: params.requestingIdentityId,
326
+ requestingProvider: params.requestingProvider,
327
+ requestingPlatformId: params.requestingPlatformId,
328
+ preferredChannel: params.preferredChannel,
329
+ contact
330
+ });
331
+ }
332
+ }),
333
+ defineTool({
334
+ name: "confirm_identity_verification",
335
+ description: "Confirm a verification by submitting the phrase the user received. Returns `{ verified, identityId, action }` where `action` is 'merged' (the verified contact already lived on another identity, which is now the survivor) or 'contact_verified' (the contact was attached to the claimed identity).",
336
+ parameters: _sinclair_typebox.Type.Object({
337
+ claimedIdentityId: _sinclair_typebox.Type.String({ description: "Identity being claimed (matches request)" }),
338
+ verificationId: _sinclair_typebox.Type.String({ description: "Verification ID returned from request_identity_verification" }),
339
+ phrase: _sinclair_typebox.Type.String({ description: "Three-word phrase the person received via mobile or email" })
340
+ }),
341
+ handler: (params) => client.confirmIdentityVerification({
342
+ claimedIdentityId: params.claimedIdentityId,
343
+ verificationId: params.verificationId,
344
+ phrase: params.phrase
345
+ })
346
+ })
347
+ ];
348
+ for (const tool of tools) api.registerTool(tool);
349
+ log.info(`Registered ${String(tools.length)} identity tools`);
350
+ api.on("message_received", async (...args) => {
351
+ const event = args[0];
352
+ const ctx = args[1];
353
+ const provider = ctx.channelId ?? "unknown";
354
+ const senderId = event.metadata?.UserId ?? event.from;
355
+ if (!senderId) return;
356
+ const cacheKey = ctx.conversationId ?? `${provider}:${senderId}`;
357
+ const cached = getCachedResolve(cacheKey);
358
+ if (cached) {
359
+ if (cached.identityId == null) return {
360
+ block: true,
361
+ blockReason: "Identity: identity not provisioned for this channel"
362
+ };
363
+ if (!cached.accessAllowed) return {
364
+ block: true,
365
+ blockReason: "Identity: access denied for this sender"
366
+ };
367
+ return;
368
+ }
369
+ try {
370
+ const r = await client.resolveIdentity({
371
+ provider,
372
+ platformId: senderId
373
+ });
374
+ setCachedResolve(cacheKey, {
375
+ identityId: r.identityId,
376
+ accessAllowed: r.accessAllowed,
377
+ status: r.status
378
+ });
379
+ if (r.identityId == null) {
380
+ log.warn(`Identity not provisioned for ${provider}:${senderId} — blocking inbound message`);
381
+ return {
382
+ block: true,
383
+ blockReason: "Identity: identity not provisioned for this channel"
384
+ };
385
+ }
386
+ if (!r.accessAllowed) return {
387
+ block: true,
388
+ blockReason: "Identity: access denied for this sender"
389
+ };
390
+ log.info(`Identity resolved: ${senderId} → ${r.identityId} (${r.status})`);
391
+ } catch (e) {
392
+ log.error(`Identity resolution failed for ${senderId}: ${e.message}`);
393
+ return {
394
+ block: true,
395
+ blockReason: "Identity: identity service unavailable — access denied (fail-closed)"
396
+ };
397
+ }
398
+ }, { priority: 100 });
399
+ const beforeToolCallStub = (event, ctx) => {
400
+ if (ctx.authMethod === "token" && ctx.tokenPermissions !== void 0) {
401
+ const blocked = applyGateMode(evaluateAgentExec(ctx.tokenPermissions, {
402
+ agentId: ctx.agentId,
403
+ toolName: event.toolName,
404
+ toolArgs: event.toolArgs
405
+ }), resolveToolGatingMode(), event.toolName);
406
+ return Promise.resolve(blocked);
407
+ }
408
+ return Promise.resolve(void 0);
409
+ };
410
+ api.on("before_tool_call", (...args) => beforeToolCallStub(args[0], args[1]), { priority: 100 });
411
+ log.info("Alfe Identity plugin activated");
412
+ }
413
+ };
414
+ //#endregion
415
+ Object.defineProperty(exports, "plugin", {
416
+ enumerable: true,
417
+ get: function() {
418
+ return plugin;
419
+ }
420
+ });