@haneinfo/commands 0.0.0-stage → 0.1.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.
Files changed (40) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +200 -2
  3. package/agent-guide.md +9 -0
  4. package/dist/authorizer.d.ts +73 -0
  5. package/dist/authorizer.d.ts.map +1 -0
  6. package/dist/authorizer.js +245 -0
  7. package/dist/authorizer.js.map +1 -0
  8. package/dist/command-tool-error.d.ts +10 -0
  9. package/dist/command-tool-error.d.ts.map +1 -0
  10. package/dist/command-tool-error.js +25 -0
  11. package/dist/command-tool-error.js.map +1 -0
  12. package/dist/define-command.d.ts +49 -0
  13. package/dist/define-command.d.ts.map +1 -0
  14. package/dist/define-command.js +175 -0
  15. package/dist/define-command.js.map +1 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +17 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/nest/commands-web.executor.d.ts +38 -0
  21. package/dist/nest/commands-web.executor.d.ts.map +1 -0
  22. package/dist/nest/commands-web.executor.js +115 -0
  23. package/dist/nest/commands-web.executor.js.map +1 -0
  24. package/dist/nest/commands-web.module.d.ts +12 -0
  25. package/dist/nest/commands-web.module.d.ts.map +1 -0
  26. package/dist/nest/commands-web.module.js +38 -0
  27. package/dist/nest/commands-web.module.js.map +1 -0
  28. package/dist/nest/index.d.ts +3 -0
  29. package/dist/nest/index.d.ts.map +1 -0
  30. package/dist/nest/index.js +10 -0
  31. package/dist/nest/index.js.map +1 -0
  32. package/dist/registry.d.ts +77 -0
  33. package/dist/registry.d.ts.map +1 -0
  34. package/dist/registry.js +202 -0
  35. package/dist/registry.js.map +1 -0
  36. package/dist/types.d.ts +101 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +3 -0
  39. package/dist/types.js.map +1 -0
  40. package/package.json +69 -3
package/LICENSE ADDED
@@ -0,0 +1,14 @@
1
+ Copyright (c) 2026 Haneinfo. All Rights Reserved.
2
+
3
+ This software and associated documentation files (the "Software") are the proprietary and
4
+ confidential property of Haneinfo. No part of the Software may be copied, modified, merged,
5
+ published, distributed, sublicensed, or sold without the prior written permission of Haneinfo.
6
+
7
+ The Software is provided for internal use by Haneinfo and its authorized personnel only, and is
8
+ NOT licensed for external distribution or open-source use.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
11
+ NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
12
+ NONINFRINGEMENT. IN NO EVENT SHALL HANEINFO BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
13
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
14
+ THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # @haneinfo/commands
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared command declarations, validation, and surface-aware registry for Web and MCP (`@haneinfo/commands`).
4
+
5
+ ## Purpose
6
+
7
+ `@haneinfo/commands` provides the platform's single command declaration contract shared across Web APIs and MCP endpoints (`/mcp` and `/mcp/admin`), along with startup validation, a surface-aware command registry, the shared command authorizer, capability-flag helpers, and the Web NestJS adapter (`@haneinfo/commands/nest`).
8
+
9
+ ## Usage: `defineCommand`
10
+
11
+ `defineCommand` validates a command against the platform contract at call time and returns the same object, frozen.
12
+
13
+ ### Read Command Example
14
+
15
+ ```ts
16
+ import { z } from 'zod';
17
+ import { defineCommand } from '@haneinfo/commands';
18
+
19
+ export const getDocumentCommand = defineCommand({
20
+ name: 'docs.document.get',
21
+ description: 'Get a document by ID.',
22
+ schemaVersion: 1,
23
+ inputSchema: z.object({ id: z.string().min(1) }),
24
+ outputSchema: z.object({ id: z.string(), title: z.string() }),
25
+ permissions: ['DOCS_READ'],
26
+ match: 'all',
27
+ scope: 'docs:document:read',
28
+ access: 'read',
29
+ surfaces: ['web', 'mcp'],
30
+ async handler(actor, input, _tx) {
31
+ return { id: input.id, title: `Doc for ${actor.actingUserId ?? 'anonymous'}` };
32
+ },
33
+ });
34
+ ```
35
+
36
+ ### Write Command Example
37
+
38
+ ```ts
39
+ import { z } from 'zod';
40
+ import { defineCommand } from '@haneinfo/commands';
41
+
42
+ export const createDocumentCommand = defineCommand({
43
+ name: 'docs.document.create',
44
+ description: 'Create a new document.',
45
+ schemaVersion: 1,
46
+ inputSchema: z.object({ title: z.string().min(1) }),
47
+ permissions: ['DOCS_WRITE'],
48
+ match: 'all',
49
+ scope: 'docs:document:write',
50
+ access: 'write',
51
+ confirmation: 'required',
52
+ surfaces: ['web', 'mcp'],
53
+ async handler(_actor, input, _tx) {
54
+ return { created: input.title };
55
+ },
56
+ });
57
+ ```
58
+
59
+ ## Validation Rules & Error Codes
60
+
61
+ `defineCommand` and `CommandRegistry` validate every command and throw `CommandDefinitionError` (with `error.code` and `error.command`) on violation:
62
+
63
+ | Rule | Error Code | Requirement |
64
+ | --- | --- | --- |
65
+ | 1 | `invalid-name` | `name` must be a non-empty string without whitespace. |
66
+ | 2 | `invalid-schema-version` | `schemaVersion` must be a positive integer. |
67
+ | 3 | `missing-description` | When `surfaces` includes `'mcp'` or `'mcp-admin'`, `description` must be a non-empty trimmed string. |
68
+ | 4 | `missing-access` | `access` must be `'read'` or `'write'`. |
69
+ | 5a | `read-confirmation-forbidden` | When `access === 'read'`, `confirmation` and `exemptReason` must not be declared. |
70
+ | 5b | `missing-confirmation` | When `access === 'write'`, `confirmation` must be `'required'` or `'exempt'`. |
71
+ | 5c | `missing-exempt-reason` | When `access === 'write'` and `confirmation === 'exempt'`, `exemptReason` must be a non-empty trimmed string. |
72
+ | 6 | `admin-write-requires-confirmation` | `access === 'write'` on `'mcp-admin'` must not declare `confirmation: 'exempt'`. |
73
+ | 7 | `invalid-surfaces` | `surfaces` must be a non-empty array of unique `'web' \| 'mcp' \| 'mcp-admin'` values. |
74
+ | 8a | `invalid-permissions` | `permissions` must be an array of unique non-empty strings. |
75
+ | 8b | `missing-resource-acl-reason` | When `permissions` is empty (`[]`), `resourceAclReason` must be a non-empty trimmed string. |
76
+ | 8c | `unexpected-resource-acl-reason` | When `permissions` is non-empty, `resourceAclReason` must not be declared. |
77
+ | 8d | `admin-resource-acl-forbidden` | Commands on `'mcp-admin'` must not have empty `permissions` (resource-ACL-only commands are forbidden on `'mcp-admin'`). |
78
+ | 9 | `invalid-match` | `match` must be `'any'` or `'all'`. |
79
+ | 10 | `invalid-scope` | `scope` must parse via `parseScope` with exactly three `<app>:<resource>:<action>` segments and no `*` wildcards. |
80
+ | 11 | `admission-policy-surface` | `admissionPolicy` defaults to `'required'`; `'exempt'` or `'independent'` requires `surfaces` to be exactly `['web']`. |
81
+ | 12a | `invalid-schema` | `inputSchema` must be provided (and `outputSchema` must be an object if provided). |
82
+ | 12b | `invalid-handler` | `handler` must be a function. |
83
+
84
+ ## Registry Lifecycle (`register` → `seal` → `list`)
85
+
86
+ ```ts
87
+ import { createCommandRegistry } from '@haneinfo/commands';
88
+
89
+ const registry = createCommandRegistry();
90
+
91
+ // 1. Register static commands, external tool groups, and dynamic sources at startup
92
+ registry.register(getDocumentCommand);
93
+ registry.register(createDocumentCommand);
94
+ // registry.registerGroup(externalAdapter);
95
+ // registry.registerSource(dynamicSource);
96
+
97
+ // 2. Seal after startup registration completes; further registrations throw 'registry-sealed'
98
+ registry.seal();
99
+
100
+ // 3. Query by surface (deterministically sorted by name) or look up a single command
101
+ const mcpCommands = registry.list('mcp');
102
+ const adminDoc = registry.get('docs.document.get', 'mcp-admin'); // undefined (not on 'mcp-admin')
103
+ const exemptions = registry.listConfirmationExemptions(); // write commands with confirmation: 'exempt'
104
+ const resourceAcl = registry.listResourceAclCommands(); // commands with permissions: []
105
+ const sourceErrors = registry.sourceErrors(); // failing dynamic sources isolated during list()/get()
106
+ ```
107
+
108
+ ### Dynamic Source Isolation & `CommandToolError`
109
+
110
+ - **Dynamic source isolation**: If a registered `DynamicCommandSource` throws or yields invalid/duplicate commands during `list()` or `get()`, the failing source is skipped (with a single warning logged per source) and recorded in `registry.sourceErrors()` so healthy commands continue to be served. Static registration (`register`) and `registerGroup` still throw immediately on validation or duplicate errors.
111
+ - **Dynamic sources produce employee reads only**: a dynamic command that is a write or exposes `mcp-admin` makes its source fail (recorded with `phase: 'commands'`), so isolating a failing source can never hide or expose a write.
112
+ - **Refreshing sources**: call `await registry.refreshSources()` before each list or call (mcp-server does this for `tools/list` and `tools/call`); each source throttles itself. A failing `refresh()` is recorded with `phase: 'refresh'` and the source keeps serving its previous commands.
113
+ - **`CommandToolError`**: Exported from `@haneinfo/commands` (`new CommandToolError(payload, message?)`) so command handlers can return domain-level tool errors with a JSON-serializable `payload` without depending on `@haneinfo/mcp-server`.
114
+
115
+ ### Registry Error Codes (`CommandRegistryError`)
116
+
117
+ | Error Code | Condition |
118
+ | --- | --- |
119
+ | `duplicate-command` | A command with the same `name` is already registered (static, group, or dynamic). |
120
+ | `duplicate-group` | An `ExternalToolGroupAdapter` with the same `groupId` is already registered. |
121
+ | `duplicate-source` | A `DynamicCommandSource` with the same `sourceId` is already registered. |
122
+ | `registry-sealed` | `register`, `registerGroup`, or `registerSource` is called after `seal()`. |
123
+
124
+ ## Authorizer (`createCommandAuthorizer`)
125
+
126
+ `createCommandAuthorizer({ rbac, scopeMatcher?, lockTimeoutMs })` enforces the platform authorization pipeline in strict order (`mcp-connector-contract.md` §3.3; 1A §4):
127
+
128
+ 1. **Step 1 — Principal / Surface Match & Command Availability**:
129
+ - `'m2m-api-key'` → `'web'`, `'web-session'` → `'web'`, `'oauth-employee'` → `'mcp'`, `'oauth-admin'` → `'mcp-admin'`. Mismatches return `surface_mismatch`.
130
+ - If `command.surfaces` does not include `actor.surface`, returns `command_unavailable`.
131
+ 2. **Step 2 — App Admission**:
132
+ - Skipped when `command.admissionPolicy` is `'exempt'` or `'independent'`.
133
+ - When `'required'` (default):
134
+ - General users (`web-session`, `oauth-*`): requires `actingUserId !== null`, `isActive === true`, `isServiceAccount === false`, and at least one role from `rbac.rolesForUser(actingUserId)`.
135
+ - M2M (`m2m-api-key`): requires `actingUserId !== null`, `isActive === true`, `isServiceAccount === true`, and a non-empty `machineAuthorization.roleNames`.
136
+ - Denies with `app_admission_denied`.
137
+ 3. **Step 3 — Scope**:
138
+ - `oauth-employee` / `oauth-admin`: exact string match against `command.scope` (no `*` wildcards).
139
+ - `m2m-api-key`: delegates to `scopeMatcher.matches`; denied if `scopeMatcher` is not provided.
140
+ - `web-session`: not checked.
141
+ - Denies with `insufficient_scope`.
142
+ 4. **Step 4 — RBAC**:
143
+ - Flattens `rbac.rolesForUser(actingUserId)` for general users, or uses `machineAuthorization` for M2M.
144
+ - When `command.permissions` is empty (`[]`, resource-ACL command), skips `hasPermissions` (still requires step 2 App admission). Otherwise evaluates via `@haneinfo/plugin-api`'s `hasPermissions(authorization, command.permissions, command.match)`. (`READ_ALL` does not cover non-read permissions such as `REPORT_RUN`.)
145
+ - Denies with `insufficient_permission`.
146
+ 5. **Step 5 — Write-Transaction Recheck (`authorizeWriteInTransaction`)**:
147
+ - Called inside a `ReadCommitted` transaction for `access: 'write'` commands.
148
+ - Executes `SET LOCAL lock_timeout = '<lockTimeoutMs>ms'`.
149
+ - **General users**: acquires `pg_advisory_xact_lock_shared(hashtext('rbac:user-roles'), hashtext(userId))`, queries `user_roles` ordered by `role_id ASC` and acquires `pg_advisory_xact_lock_shared(hashtext('rbac:role'), hashtext(roleId))` for each role, locks the user row with `SELECT is_active, is_service_account FROM users WHERE id = $1 FOR SHARE`, then calls `rbac.rolesForUser(userId, tx)` and re-evaluates steps 2–4.
150
+ - **M2M (`m2m-api-key`)**: locks the bound service account row with `SELECT is_active, is_service_account FROM users WHERE id = $1 FOR SHARE` and re-verifies `isActive === true` and `isServiceAccount === true` using the request-provided `machineAuthorization`.
151
+ - Returns `lock_timeout` on PostgreSQL `55P03` / lock-timeout errors, or `authorization_stale` if re-evaluation fails.
152
+
153
+ ### Why `lockTimeoutMs` Is Required
154
+
155
+ The platform contract intentionally does not prescribe a default `lockTimeoutMs`. Lock wait budgets depend on each App's write concurrency and latency SLOs (or W5 MCP transport limits), so `createCommandAuthorizer` and `CommandsWebModule.forRoot` require a positive integer `lockTimeoutMs` and fail fast at startup if omitted or invalid.
156
+
157
+ ### Denial Codes & Web HTTP Mapping
158
+
159
+ | Code | Step | Web HTTP Status |
160
+ | --- | --- | --- |
161
+ | `surface_mismatch` | 1 | `403` |
162
+ | `command_unavailable` | 1 (or missing in registry) | `404` |
163
+ | `app_admission_denied` | 2 | `403` |
164
+ | `insufficient_scope` | 3 | `403` |
165
+ | `insufficient_permission` | 4 | `403` |
166
+ | `lock_timeout` | 5 | `409` |
167
+ | `authorization_stale` | 5 | `403` |
168
+
169
+ ### Capability Flags (`holdsPermissions`)
170
+
171
+ `holdsPermissions(authorization, permissions, match)` delegates directly to `hasPermissions` from `@haneinfo/plugin-api`. It is intended strictly for UI/display capability flags and **must not** be used as an entry authorization gate.
172
+
173
+ ## Web NestJS Adapter (`@haneinfo/commands/nest`)
174
+
175
+ Import `CommandsWebModule` and `CommandWebExecutor` from `@haneinfo/commands/nest`. `@nestjs/common` and `@haneinfo/plugin-host-nest` are optional peer dependencies and are never imported by the root `@haneinfo/commands` entry point.
176
+
177
+ ```ts
178
+ import { Module } from '@nestjs/common';
179
+ import { CommandsWebModule } from '@haneinfo/commands/nest';
180
+
181
+ @Module({
182
+ imports: [
183
+ CommandsWebModule.forRoot({
184
+ registry: appCommandRegistry,
185
+ lockTimeoutMs: 2000,
186
+ }),
187
+ ],
188
+ })
189
+ export class AppCommandsModule {}
190
+ ```
191
+
192
+ `CommandWebExecutor.execute(request, commandName, rawInput)` resolves the host-attached `Principal` from `request.user` (`401` if absent), looks up the command on `'web'` (`404 command_unavailable`), validates `rawInput` with `command.inputSchema` (`400 invalid_input` without leaking Zod internals), loads local account flags from `IDENTITY_STORE`, runs `authorize`, and executes `read` commands with `PRISMA` or `write` commands inside `PRISMA.$transaction(..., { isolationLevel: 'ReadCommitted' })` with `authorizeWriteInTransaction` before invoking `command.handler`.
193
+
194
+ ## Known Gaps
195
+
196
+ - **M2M API key revocation / key-role change race**: For `m2m-api-key` callers, step 5 (`authorizeWriteInTransaction`) locks and re-checks the bound service account row (`users.is_active`, `users.is_service_account`) via `FOR SHARE`, and keeps using the request's `machineAuthorization` without acquiring `rbac:user-roles` or `rbac:role` advisory locks. Concurrent API key revocation or key-role modification between authentication and write commit is not covered until `@haneinfo/m2m-api-key` provides an in-transaction key re-verification port.
197
+
198
+ ## Runtime Constraints
199
+
200
+ - Pure Node.js (`>=22.0.0`), CommonJS.
201
+ - Root entry runtime dependencies are restricted to `@haneinfo/plugin-api`. `zod` is used only via `import type` at root, and NestJS / Prisma are never imported by the root entry.
package/agent-guide.md ADDED
@@ -0,0 +1,9 @@
1
+ # @haneinfo/commands Agent Guide
2
+
3
+ Read [README.md](README.md) for the public API, validation rules, and registry lifecycle.
4
+
5
+ - Keep runtime dependencies strictly limited to `@haneinfo/plugin-api`. Use `import type` for `zod` so `dist/` never requires `zod`, NestJS, or Prisma at runtime.
6
+ - Keep `CommandDefinition`, `CommandActor`, `CommandToolError`, `DynamicCommandSource`, `ExternalToolGroupAdapter`, and `ScopeCatalogEntry` aligned with `specs/topics/mcp-connector-contract.md` (§3.1, §3.2, §5.2, §9.1) and `specs/decisions/202611-ee5a-mcp-connector-platform-contract.md` (§4, §6).
7
+ - Read commands (`access: 'read'`) must not declare `confirmation` or `exemptReason`; write commands must declare `confirmation`; `description` is required for `mcp`/`mcp-admin` surfaces; `permissions: []` requires `resourceAclReason` and is forbidden on `mcp-admin`.
8
+ - Dynamic sources yield employee reads only; call `registry.refreshSources()` before each list or call; failures are isolated in `refreshSources()`/`list()`/`get()` and exposed via `registry.sourceErrors()`; `listConfirmationExemptions()` returns writes only; `listResourceAclCommands()` lists `permissions: []` commands.
9
+ - Run `pnpm --filter @haneinfo/commands build`, `pnpm --filter @haneinfo/commands typecheck`, and `pnpm --filter @haneinfo/commands test` after changes.
@@ -0,0 +1,73 @@
1
+ import { type PrincipalAuthorization, type RbacPolicyPort, type RoleGrant, type ScopeMatcherPort } from '@haneinfo/plugin-api';
2
+ import type { ZodType } from 'zod';
3
+ import type { CommandActor, CommandDefinition } from './types';
4
+ /**
5
+ * Denial codes returned by the command authorizer (`mcp-connector-contract.md` §3.3, §4; 1A §4).
6
+ */
7
+ export type AuthorizationDenialCode = 'surface_mismatch' | 'command_unavailable' | 'app_admission_denied' | 'insufficient_scope' | 'insufficient_permission' | 'lock_timeout' | 'authorization_stale';
8
+ /** Authorization step index (`1`–`4` pre-flight, `5` write-transaction recheck). */
9
+ export type AuthorizationStep = 1 | 2 | 3 | 4 | 5;
10
+ /** Decision returned by {@link CommandAuthorizer.authorize} and {@link CommandAuthorizer.authorizeWriteInTransaction}. */
11
+ export type AuthorizationDecision = {
12
+ ok: true;
13
+ authorization: PrincipalAuthorization;
14
+ } | {
15
+ ok: false;
16
+ code: AuthorizationDenialCode;
17
+ step: AuthorizationStep;
18
+ };
19
+ /**
20
+ * Minimal transactional SQL interface compatible with Prisma's `TransactionClient` and `pg` shims.
21
+ */
22
+ export interface AuthorizerTxClient {
23
+ $executeRawUnsafe(sql: string, ...values: unknown[]): Promise<unknown>;
24
+ $queryRawUnsafe<T = unknown>(sql: string, ...values: unknown[]): Promise<T>;
25
+ }
26
+ /** Dependencies required to construct a {@link CommandAuthorizer}. */
27
+ export interface CommandAuthorizerDeps {
28
+ rbac: Pick<RbacPolicyPort, 'rolesForUser' | 'flatten'>;
29
+ scopeMatcher?: ScopeMatcherPort;
30
+ /** Required positive integer in milliseconds for `SET LOCAL lock_timeout` in step 5. */
31
+ lockTimeoutMs: number;
32
+ }
33
+ /** Input passed to {@link CommandAuthorizer.authorize}. */
34
+ export interface AuthorizeCommandInput<TTx = unknown> {
35
+ actor: CommandActor;
36
+ command: CommandDefinition<ZodType, ZodType | undefined, TTx>;
37
+ machineAuthorization?: PrincipalAuthorization;
38
+ preloadedRoles?: readonly RoleGrant[];
39
+ }
40
+ /** Input passed to {@link CommandAuthorizer.authorizeWriteInTransaction}. */
41
+ export interface AuthorizeWriteInTransactionInput<TTx = unknown> {
42
+ actor: CommandActor;
43
+ command: CommandDefinition<ZodType, ZodType | undefined, TTx>;
44
+ machineAuthorization?: PrincipalAuthorization;
45
+ preloadedRoles?: never;
46
+ }
47
+ /** Shared command authorizer enforcing steps 1–5 (`mcp-connector-contract.md` §3.3; 1A §4). */
48
+ export interface CommandAuthorizer {
49
+ authorize(input: AuthorizeCommandInput): Promise<AuthorizationDecision>;
50
+ authorizeWriteInTransaction(input: AuthorizeWriteInTransactionInput, tx: AuthorizerTxClient): Promise<AuthorizationDecision>;
51
+ }
52
+ /**
53
+ * Capability-flag helper for UI/display queries (e.g. `holdsPermission`).
54
+ *
55
+ * Delegates directly to `@haneinfo/plugin-api`'s `hasPermissions`.
56
+ * MUST NOT be used as an entry authorization gate (1A §4; `mcp-connector-contract.md` §3.3).
57
+ */
58
+ export declare function holdsPermissions(authorization: PrincipalAuthorization, permissions: readonly string[], match: 'any' | 'all'): boolean;
59
+ /**
60
+ * Evaluates step 2 App admission for interactive and OAuth user principals
61
+ * (`mcp-connector-contract.md` §3.3; 1A §4).
62
+ *
63
+ * Requires a non-empty `actingUserId`, `isActive === true`, `isServiceAccount === false`,
64
+ * and at least one role returned by `rbac.rolesForUser(actingUserId, transaction)`.
65
+ */
66
+ export declare function checkAppAdmission(actor: CommandActor, rbac: Pick<RbacPolicyPort, 'rolesForUser'>, transaction?: unknown): Promise<boolean>;
67
+ /**
68
+ * Creates the single shared command authorizer (`mcp-connector-contract.md` §3.3; 1A §4).
69
+ *
70
+ * Fails fast on construction if `lockTimeoutMs` is not a positive integer.
71
+ */
72
+ export declare function createCommandAuthorizer(deps: CommandAuthorizerDeps): CommandAuthorizer;
73
+ //# sourceMappingURL=authorizer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorizer.d.ts","sourceRoot":"","sources":["../src/authorizer.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,KAAK,EACV,YAAY,EACZ,iBAAiB,EAGlB,MAAM,SAAS,CAAC;AAEjB;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAC/B,kBAAkB,GAClB,qBAAqB,GACrB,sBAAsB,GACtB,oBAAoB,GACpB,yBAAyB,GACzB,cAAc,GACd,qBAAqB,CAAC;AAE1B,oFAAoF;AACpF,MAAM,MAAM,iBAAiB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD,0HAA0H;AAC1H,MAAM,MAAM,qBAAqB,GAC7B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,aAAa,EAAE,sBAAsB,CAAA;CAAE,GACnD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,uBAAuB,CAAC;IAAC,IAAI,EAAE,iBAAiB,CAAA;CAAE,CAAC;AAE1E;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACvE,eAAe,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC7E;AAED,sEAAsE;AACtE,MAAM,WAA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AAW,CAAC,EAAE,OAAO,GACpB,OAAO,CAAC,OAAO,CAAC,CAYlB;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,qBAAqB,GAAG,iBAAiB,CAkMtF"}
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.holdsPermissions = holdsPermissions;
4
+ exports.checkAppAdmission = checkAppAdmission;
5
+ exports.createCommandAuthorizer = createCommandAuthorizer;
6
+ const plugin_api_1 = require("@haneinfo/plugin-api");
7
+ const EXPECTED_SURFACE_BY_PRINCIPAL = {
8
+ 'm2m-api-key': 'web',
9
+ 'oauth-employee': 'mcp',
10
+ 'oauth-admin': 'mcp-admin',
11
+ 'web-session': 'web',
12
+ };
13
+ function assertValidLockTimeoutMs(lockTimeoutMs) {
14
+ if (typeof lockTimeoutMs !== 'number' || !Number.isInteger(lockTimeoutMs) || lockTimeoutMs <= 0) {
15
+ throw new RangeError('lockTimeoutMs must be a positive integer (milliseconds).');
16
+ }
17
+ }
18
+ function isLockTimeoutError(error) {
19
+ if (error === null || typeof error !== 'object') {
20
+ return false;
21
+ }
22
+ const record = error;
23
+ if (record.code === '55P03') {
24
+ return true;
25
+ }
26
+ if (record.meta !== null &&
27
+ typeof record.meta === 'object' &&
28
+ record.meta.code === '55P03') {
29
+ return true;
30
+ }
31
+ if (typeof record.message === 'string') {
32
+ const msg = record.message.toLowerCase();
33
+ if (msg.includes('lock timeout') ||
34
+ msg.includes('canceling statement due to lock timeout') ||
35
+ msg.includes('lock_not_available')) {
36
+ return true;
37
+ }
38
+ }
39
+ if (record.cause && record.cause !== error) {
40
+ return isLockTimeoutError(record.cause);
41
+ }
42
+ return false;
43
+ }
44
+ function checkStep1(actor, command) {
45
+ if (EXPECTED_SURFACE_BY_PRINCIPAL[actor.principalKind] !== actor.surface) {
46
+ return { ok: false, code: 'surface_mismatch', step: 1 };
47
+ }
48
+ if (!command.surfaces.includes(actor.surface)) {
49
+ return { ok: false, code: 'command_unavailable', step: 1 };
50
+ }
51
+ return null;
52
+ }
53
+ function checkStep3(actor, command, scopeMatcher) {
54
+ switch (actor.principalKind) {
55
+ case 'oauth-employee':
56
+ case 'oauth-admin':
57
+ if (!actor.scopes.includes(command.scope)) {
58
+ return { ok: false, code: 'insufficient_scope', step: 3 };
59
+ }
60
+ return null;
61
+ case 'm2m-api-key':
62
+ if (!scopeMatcher?.matches([...actor.scopes], command.scope)) {
63
+ return { ok: false, code: 'insufficient_scope', step: 3 };
64
+ }
65
+ return null;
66
+ case 'web-session':
67
+ return null;
68
+ }
69
+ }
70
+ /**
71
+ * Capability-flag helper for UI/display queries (e.g. `holdsPermission`).
72
+ *
73
+ * Delegates directly to `@haneinfo/plugin-api`'s `hasPermissions`.
74
+ * MUST NOT be used as an entry authorization gate (1A §4; `mcp-connector-contract.md` §3.3).
75
+ */
76
+ function holdsPermissions(authorization, permissions, match) {
77
+ return (0, plugin_api_1.hasPermissions)(authorization, permissions, match);
78
+ }
79
+ /**
80
+ * Evaluates step 2 App admission for interactive and OAuth user principals
81
+ * (`mcp-connector-contract.md` §3.3; 1A §4).
82
+ *
83
+ * Requires a non-empty `actingUserId`, `isActive === true`, `isServiceAccount === false`,
84
+ * and at least one role returned by `rbac.rolesForUser(actingUserId, transaction)`.
85
+ */
86
+ async function checkAppAdmission(actor, rbac, transaction) {
87
+ if (actor.principalKind === 'm2m-api-key' ||
88
+ actor.actingUserId === null ||
89
+ actor.actingUserId.length === 0 ||
90
+ actor.isActive !== true ||
91
+ actor.isServiceAccount !== false) {
92
+ return false;
93
+ }
94
+ const roles = await rbac.rolesForUser(actor.actingUserId, transaction);
95
+ return roles.length > 0;
96
+ }
97
+ /**
98
+ * Creates the single shared command authorizer (`mcp-connector-contract.md` §3.3; 1A §4).
99
+ *
100
+ * Fails fast on construction if `lockTimeoutMs` is not a positive integer.
101
+ */
102
+ function createCommandAuthorizer(deps) {
103
+ if (!deps?.rbac) {
104
+ throw new TypeError('CommandAuthorizer requires an rbac dependency.');
105
+ }
106
+ assertValidLockTimeoutMs(deps.lockTimeoutMs);
107
+ const { rbac, scopeMatcher, lockTimeoutMs } = deps;
108
+ async function evaluateSteps2To4(actor, command, machineAuthorization, preloadedRoles, tx) {
109
+ const admissionPolicy = command.admissionPolicy ?? 'required';
110
+ let userRoles = preloadedRoles;
111
+ // Step 2: App admission
112
+ if (admissionPolicy === 'required') {
113
+ if (actor.principalKind === 'm2m-api-key') {
114
+ if (actor.actingUserId === null ||
115
+ actor.actingUserId.length === 0 ||
116
+ !machineAuthorization ||
117
+ machineAuthorization.roleNames.length === 0 ||
118
+ actor.isActive !== true ||
119
+ actor.isServiceAccount !== true) {
120
+ return { ok: false, code: 'app_admission_denied', step: 2 };
121
+ }
122
+ }
123
+ else {
124
+ // Reuse the step 2 role lookup in step 4 without bypassing cheap preconditions in checkAppAdmission.
125
+ const rbacForAdmission = userRoles !== undefined
126
+ ? { rolesForUser: async () => [...userRoles] }
127
+ : {
128
+ rolesForUser: async (userId, transaction) => {
129
+ const roles = await rbac.rolesForUser(userId, transaction);
130
+ userRoles = roles;
131
+ return roles;
132
+ },
133
+ };
134
+ if (!(await checkAppAdmission(actor, rbacForAdmission, tx))) {
135
+ return { ok: false, code: 'app_admission_denied', step: 2 };
136
+ }
137
+ }
138
+ }
139
+ // Step 3: Scope
140
+ const step3Failure = checkStep3(actor, command, scopeMatcher);
141
+ if (step3Failure) {
142
+ return step3Failure;
143
+ }
144
+ // Step 4: RBAC
145
+ let authorization;
146
+ if (actor.principalKind === 'm2m-api-key') {
147
+ if (!machineAuthorization) {
148
+ return { ok: false, code: 'insufficient_permission', step: 4 };
149
+ }
150
+ authorization = machineAuthorization;
151
+ }
152
+ else {
153
+ if (actor.actingUserId === null || actor.actingUserId.length === 0) {
154
+ return { ok: false, code: 'insufficient_permission', step: 4 };
155
+ }
156
+ userRoles ??= await rbac.rolesForUser(actor.actingUserId, tx);
157
+ authorization = rbac.flatten([...userRoles]);
158
+ }
159
+ if (command.permissions.length > 0 &&
160
+ !(0, plugin_api_1.hasPermissions)(authorization, command.permissions, command.match)) {
161
+ return { ok: false, code: 'insufficient_permission', step: 4 };
162
+ }
163
+ return { ok: true, authorization };
164
+ }
165
+ return {
166
+ async authorize({ actor, command, machineAuthorization, preloadedRoles }) {
167
+ if (actor.principalKind === 'm2m-api-key' && preloadedRoles !== undefined) {
168
+ throw new TypeError('preloadedRoles cannot be provided for m2m-api-key principals.');
169
+ }
170
+ const step1Failure = checkStep1(actor, command);
171
+ if (step1Failure) {
172
+ return step1Failure;
173
+ }
174
+ return evaluateSteps2To4(actor, command, machineAuthorization, preloadedRoles, undefined);
175
+ },
176
+ async authorizeWriteInTransaction({ actor, command, machineAuthorization }, tx) {
177
+ if (command.access !== 'write') {
178
+ throw new TypeError('authorizeWriteInTransaction must only be called for write commands.');
179
+ }
180
+ const step1Failure = checkStep1(actor, command);
181
+ if (step1Failure) {
182
+ return step1Failure;
183
+ }
184
+ if (actor.actingUserId === null || actor.actingUserId.length === 0) {
185
+ return { ok: false, code: 'authorization_stale', step: 5 };
186
+ }
187
+ try {
188
+ await tx.$executeRawUnsafe(`SET LOCAL lock_timeout = '${lockTimeoutMs}ms'`);
189
+ if (actor.principalKind === 'm2m-api-key') {
190
+ if (!machineAuthorization) {
191
+ return { ok: false, code: 'authorization_stale', step: 5 };
192
+ }
193
+ const userRows = await tx.$queryRawUnsafe('SELECT is_active, is_service_account FROM users WHERE id = $1 FOR SHARE', actor.actingUserId);
194
+ const userRow = userRows[0];
195
+ if (userRow?.is_active !== true || userRow.is_service_account !== true) {
196
+ return { ok: false, code: 'authorization_stale', step: 5 };
197
+ }
198
+ const refreshedActor = {
199
+ ...actor,
200
+ isActive: userRow.is_active,
201
+ isServiceAccount: userRow.is_service_account,
202
+ };
203
+ const recheck = await evaluateSteps2To4(refreshedActor, command, machineAuthorization, undefined, tx);
204
+ if (!recheck.ok) {
205
+ return { ok: false, code: 'authorization_stale', step: 5 };
206
+ }
207
+ return recheck;
208
+ }
209
+ // General user (web-session, oauth-employee, oauth-admin):
210
+ // Step 5a: Shared advisory lock on user-roles
211
+ await tx.$executeRawUnsafe('SELECT pg_advisory_xact_lock_shared(hashtext($1), hashtext($2))', 'rbac:user-roles', actor.actingUserId);
212
+ // Step 5b: Read role IDs ordered ascending and acquire shared advisory locks in fixed order
213
+ const roleRows = await tx.$queryRawUnsafe('SELECT role_id FROM user_roles WHERE user_id = $1 ORDER BY role_id ASC', actor.actingUserId);
214
+ for (const row of roleRows) {
215
+ await tx.$executeRawUnsafe('SELECT pg_advisory_xact_lock_shared(hashtext($1), hashtext($2))', 'rbac:role', row.role_id);
216
+ }
217
+ // Step 5c: Lock user row FOR SHARE
218
+ const userRows = await tx.$queryRawUnsafe('SELECT is_active, is_service_account FROM users WHERE id = $1 FOR SHARE', actor.actingUserId);
219
+ const userRow = userRows[0];
220
+ if (!userRow) {
221
+ return { ok: false, code: 'authorization_stale', step: 5 };
222
+ }
223
+ // Step 5d: Recompute authorization on the same tx and re-run steps 2–4
224
+ const roles = await rbac.rolesForUser(actor.actingUserId, tx);
225
+ const refreshedActor = {
226
+ ...actor,
227
+ isActive: userRow.is_active,
228
+ isServiceAccount: userRow.is_service_account,
229
+ };
230
+ const recheck = await evaluateSteps2To4(refreshedActor, command, undefined, roles, tx);
231
+ if (!recheck.ok) {
232
+ return { ok: false, code: 'authorization_stale', step: 5 };
233
+ }
234
+ return recheck;
235
+ }
236
+ catch (error) {
237
+ if (isLockTimeoutError(error)) {
238
+ return { ok: false, code: 'lock_timeout', step: 5 };
239
+ }
240
+ throw error;
241
+ }
242
+ },
243
+ };
244
+ }
245
+ //# sourceMappingURL=authorizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorizer.js","sourceRoot":"","sources":["../src/authorizer.ts"],"names":[],"mappings":";;AAiKA,4CAMC;AASD,8CAgBC;AAOD,0DAkMC;AAzYD,qDAM8B;AAsE9B,MAAM,6BAA6B,GAA2D;IAC5F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BACF,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;gBAC5B,IAAI,CAAC,OAAO,EAAE,CAAC;oBACb,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;gBAC7D,CAAC;gBAED,uEAAuE;gBACvE,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBAC9D,MAAM,cAAc,GAAiB;oBACnC,GAAG,KAAK;oBACR,QAAQ,EAAE,OAAO,CAAC,SAAS;oBAC3B,gBAAgB,EAAE,OAAO,CAAC,kBAAkB;iBAC7C,CAAC;gBACF,MAAM,OAAO,GAAG,MAAM,iBAAiB,CAAC,cAAc,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;gBACvF,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;oBAChB,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;gBAC7D,CAAC;gBACD,OAAO,OAAO,CAAC;YACjB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC9B,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;gBACtD,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Serializable domain/business error thrown by a command handler to return a structured
3
+ * `isError: true` MCP tool result without depending on `@haneinfo/mcp-server`
4
+ * (`mcp-connector-contract.md` §9.2; W5-04b).
5
+ */
6
+ export declare class CommandToolError<TPayload = unknown> extends Error {
7
+ readonly payload: TPayload;
8
+ constructor(payload: TPayload, message?: string);
9
+ }
10
+ //# sourceMappingURL=command-tool-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-tool-error.d.ts","sourceRoot":"","sources":["../src/command-tool-error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,gBAAgB,CAAC,QAAQ,GAAG,OAAO,CAAE,SAAQ,KAAK;IAC7D,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;gBAEf,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,MAAM;CAehD"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommandToolError = void 0;
4
+ /**
5
+ * Serializable domain/business error thrown by a command handler to return a structured
6
+ * `isError: true` MCP tool result without depending on `@haneinfo/mcp-server`
7
+ * (`mcp-connector-contract.md` §9.2; W5-04b).
8
+ */
9
+ class CommandToolError extends Error {
10
+ constructor(payload, message) {
11
+ super(message ??
12
+ (typeof payload === 'string'
13
+ ? payload
14
+ : payload !== null &&
15
+ typeof payload === 'object' &&
16
+ 'error' in payload &&
17
+ typeof payload.error === 'string'
18
+ ? payload.error
19
+ : 'Command tool error'));
20
+ this.name = 'CommandToolError';
21
+ this.payload = payload;
22
+ }
23
+ }
24
+ exports.CommandToolError = CommandToolError;
25
+ //# sourceMappingURL=command-tool-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-tool-error.js","sourceRoot":"","sources":["../src/command-tool-error.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,MAAa,gBAAqC,SAAQ,KAAK;IAG7D,YAAY,OAAiB,EAAE,OAAgB;QAC7C,KAAK,CACH,OAAO;YACL,CAAC,OAAO,OAAO,KAAK,QAAQ;gBAC1B,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,OAAO,KAAK,IAAI;oBACd,OAAO,OAAO,KAAK,QAAQ;oBAC3B,OAAO,IAAI,OAAO;oBAClB,OAAQ,OAA+B,CAAC,KAAK,KAAK,QAAQ;oBAC5D,CAAC,CAAE,OAA6B,CAAC,KAAK;oBACtC,CAAC,CAAC,oBAAoB,CAAC,CAC9B,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAlBD,4CAkBC"}