@capybara-hq/kernel 0.1.0-rc.58 → 0.1.0-rc.59

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 (86) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/catalog/org-catalog.controller.d.ts +0 -5
  3. package/dist/catalog/org-catalog.controller.js +3 -17
  4. package/dist/catalog/org-catalog.schemas.d.ts +43 -0
  5. package/dist/catalog/org-catalog.schemas.js +43 -2
  6. package/dist/catalog/plugin-install.d.ts +2 -0
  7. package/dist/catalog/plugin-install.js +3 -3
  8. package/dist/channels/channels.schemas.d.ts +3 -0
  9. package/dist/channels/channels.schemas.js +8 -0
  10. package/dist/channels/connections.service.d.ts +17 -2
  11. package/dist/channels/connections.service.js +30 -5
  12. package/dist/channels/outbound.js +17 -0
  13. package/dist/conversations/events.d.ts +34 -0
  14. package/dist/conversations/events.js +24 -0
  15. package/dist/ctx/secrets.d.ts +8 -1
  16. package/dist/ctx/secrets.js +14 -1
  17. package/dist/db/kernel-schema.d.ts +19 -0
  18. package/dist/devices/working-root.d.ts +2 -3
  19. package/dist/errors.d.ts +10 -0
  20. package/dist/errors.js +10 -0
  21. package/dist/http/api.module.js +6 -0
  22. package/dist/identity/initial-passwords.job.d.ts +3 -3
  23. package/dist/identity/initial-passwords.job.js +7 -5
  24. package/dist/orgs/invitations.controller.d.ts +3 -11
  25. package/dist/orgs/invitations.controller.js +9 -10
  26. package/dist/orgs/invitations.service.d.ts +12 -2
  27. package/dist/orgs/invitations.service.js +14 -7
  28. package/dist/orgs/members.service.d.ts +12 -2
  29. package/dist/orgs/members.service.js +10 -8
  30. package/dist/orgs/orgs.controller.d.ts +4 -12
  31. package/dist/orgs/orgs.controller.js +10 -10
  32. package/dist/orgs/orgs.schemas.d.ts +26 -0
  33. package/dist/orgs/orgs.schemas.js +22 -0
  34. package/dist/platform/connector-person-fields.d.ts +67 -0
  35. package/dist/platform/connector-person-fields.js +129 -0
  36. package/dist/platform/exclusions.js +5 -100
  37. package/dist/platform/operation.d.ts +31 -0
  38. package/dist/platform/operation.js +3 -3
  39. package/dist/platform/ops/accounts.ops.js +1 -0
  40. package/dist/platform/ops/channels.ops.d.ts +10 -3
  41. package/dist/platform/ops/channels.ops.js +223 -5
  42. package/dist/platform/ops/connectors.ops.d.ts +22 -4
  43. package/dist/platform/ops/connectors.ops.js +664 -13
  44. package/dist/platform/ops/org-plugins.ops.d.ts +15 -2
  45. package/dist/platform/ops/org-plugins.ops.js +323 -4
  46. package/dist/platform/ops/orgs.ops.d.ts +40 -3
  47. package/dist/platform/ops/orgs.ops.js +293 -12
  48. package/dist/platform/ops/person-inputs.d.ts +30 -0
  49. package/dist/platform/ops/person-inputs.js +50 -0
  50. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  51. package/dist/platform/ops/plugins.ops.js +6 -6
  52. package/dist/platform/parity.d.ts +3 -2
  53. package/dist/platform/parity.js +40 -15
  54. package/dist/platform/person-fields.d.ts +20 -4
  55. package/dist/platform/person-fields.js +27 -5
  56. package/dist/platform/platform.module.d.ts +2 -1
  57. package/dist/platform/platform.module.js +5 -3
  58. package/dist/platform/route-schemas.js +2 -0
  59. package/dist/platform/sealed-reveals.controller.d.ts +20 -0
  60. package/dist/platform/sealed-reveals.controller.js +48 -0
  61. package/dist/platform/sealed-reveals.d.ts +52 -0
  62. package/dist/platform/sealed-reveals.js +153 -0
  63. package/dist/runtime/project/knowledge.js +24 -19
  64. package/dist/sandbox/permission-facts.d.ts +5 -1
  65. package/dist/sandbox/permission-facts.js +8 -2
  66. package/dist/setup/setup-guides.service.d.ts +5 -0
  67. package/dist/setup/setup-guides.service.js +2 -1
  68. package/dist/tools/approvals.service.js +1 -1
  69. package/dist/tools/builtins/platform.js +48 -8
  70. package/dist/tools/connectors.controller.d.ts +6 -7
  71. package/dist/tools/connectors.controller.js +4 -44
  72. package/dist/tools/connectors.schemas.d.ts +170 -1
  73. package/dist/tools/connectors.schemas.js +82 -3
  74. package/dist/tools/connectors.service.d.ts +16 -6
  75. package/dist/tools/connectors.service.js +39 -24
  76. package/dist/tools/oauth/oauth.controller.d.ts +3 -6
  77. package/dist/tools/oauth/oauth.controller.js +3 -12
  78. package/dist/tools/oauth/oauth.schemas.d.ts +14 -0
  79. package/dist/tools/oauth/oauth.schemas.js +27 -0
  80. package/dist/tools/pipeline.d.ts +7 -0
  81. package/dist/tools/pipeline.js +13 -4
  82. package/dist/tools/policy.d.ts +3 -2
  83. package/dist/tools/policy.js +4 -2
  84. package/dist/tools/registry.d.ts +7 -0
  85. package/package.json +4 -4
  86. package/src/migrations/0170_platform_sealed_reveals.sql +27 -0
package/dist/errors.js CHANGED
@@ -93,9 +93,19 @@ export const ERROR_CODES = {
93
93
  "member.not_found": 404,
94
94
  "member.already_exists": 409,
95
95
  "member.anonymous_guest": 409,
96
+ /** A Platform member operation aimed at the actor's own membership (spec §7.2: never offered). */
97
+ "member.self": 403,
98
+ /** A Platform member operation touching an owner or granting owner (spec §7.2). */
99
+ "member.owner_untouchable": 403,
100
+ /** A Platform member operation raising someone above the actor's own role (spec §7.2). */
101
+ "member.role_above_actor": 403,
96
102
  "invitation.invalid": 404,
97
103
  "invitation.expired": 410,
98
104
  "invitation.used": 409,
105
+ /** `orgs.invite` outside an approved Platform call: its link could never be shown. */
106
+ "invitation.create_needs_approval": 409,
107
+ /** No invitation link to show: read already, expired, or not a call the reader approved. */
108
+ "invitation.link_unavailable": 404,
99
109
  "extension.not_found": 404,
100
110
  /** The extension registers no tool of that name (org tool switches, layering spec A §7). */
101
111
  "extension.tool_not_found": 404,
@@ -73,6 +73,8 @@ import { InvitationsController } from "../orgs/invitations.controller.js";
73
73
  import { OrgsController } from "../orgs/orgs.controller.js";
74
74
  import { OrgsModule } from "../orgs/orgs.module.js";
75
75
  import { OrgSettingsController } from "../orgs/settings.controller.js";
76
+ import { PlatformModule } from "../platform/platform.module.js";
77
+ import { SealedRevealsController } from "../platform/sealed-reveals.controller.js";
76
78
  import { RuntimeModule } from "../runtime/runtime.module.js";
77
79
  import { ConversationStreamController } from "../runtime/stream.controller.js";
78
80
  import { SchedulesController } from "../schedules/schedules.controller.js";
@@ -114,6 +116,8 @@ const CONTROLLERS = [
114
116
  MetaController,
115
117
  MeController,
116
118
  InitialPasswordsController,
119
+ // the invitation link an org admin's agent created, read once by its approver (web parity §7.2)
120
+ SealedRevealsController,
117
121
  OrgsController,
118
122
  OrgSettingsController,
119
123
  InvitationsController,
@@ -213,6 +217,8 @@ ApiModule = __decorate([
213
217
  SkillsModule,
214
218
  IdentityModule,
215
219
  OrgsModule,
220
+ // the sealed reveals (SealedRevealsController)
221
+ PlatformModule,
216
222
  AdminModule,
217
223
  ExtensionsModule,
218
224
  CatalogModule,
@@ -1,12 +1,12 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { LockService } from "../infra/lock/lock.service.js";
3
3
  import type { KernelLogger } from "../log.js";
4
- /** The hourly cleanup of expired sealed initial passwords and person inputs (`@LockedCron`). */
4
+ /** The hourly cleanup of expired sealed initial passwords, person inputs and reveals (`@LockedCron`). */
5
5
  export declare const INITIAL_PASSWORD_CLEANUP_JOB = "initial-password-cleanup";
6
6
  /**
7
7
  * Deletes generated initial passwords nobody read before they expired (Platform tool spec §14.5
8
- * item 2) and sealed person inputs no resumed call consumed (platform web parity spec §4.3), once
9
- * per tick across replicas; the worker role's.
8
+ * item 2), sealed person inputs no resumed call consumed (platform web parity spec §4.3) and
9
+ * invitation links nobody revealed (§7.2), once per tick across replicas; the worker role's.
10
10
  */
11
11
  export declare class InitialPasswordCleanupJob {
12
12
  private readonly db;
@@ -13,13 +13,14 @@ import { LockService } from "../infra/lock/lock.service.js";
13
13
  import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
14
14
  import { KERNEL_LOGGER } from "../infra/tokens.js";
15
15
  import { deleteExpiredSealedInputs } from "../platform/sealed-inputs.js";
16
+ import { deleteExpiredSealedReveals } from "../platform/sealed-reveals.js";
16
17
  import { deleteExpiredInitialPasswords } from "./initial-passwords.js";
17
- /** The hourly cleanup of expired sealed initial passwords and person inputs (`@LockedCron`). */
18
+ /** The hourly cleanup of expired sealed initial passwords, person inputs and reveals (`@LockedCron`). */
18
19
  export const INITIAL_PASSWORD_CLEANUP_JOB = "initial-password-cleanup";
19
20
  /**
20
21
  * Deletes generated initial passwords nobody read before they expired (Platform tool spec §14.5
21
- * item 2) and sealed person inputs no resumed call consumed (platform web parity spec §4.3), once
22
- * per tick across replicas; the worker role's.
22
+ * item 2), sealed person inputs no resumed call consumed (platform web parity spec §4.3) and
23
+ * invitation links nobody revealed (§7.2), once per tick across replicas; the worker role's.
23
24
  */
24
25
  let InitialPasswordCleanupJob = class InitialPasswordCleanupJob {
25
26
  db;
@@ -33,8 +34,9 @@ let InitialPasswordCleanupJob = class InitialPasswordCleanupJob {
33
34
  async cleanup() {
34
35
  const passwords = await deleteExpiredInitialPasswords(this.db.db);
35
36
  const sealedInputs = await deleteExpiredSealedInputs(this.db.db);
36
- if (passwords > 0 || sealedInputs > 0) {
37
- this.log.info("expired sealed values deleted", { passwords, sealedInputs });
37
+ const sealedReveals = await deleteExpiredSealedReveals(this.db.db);
38
+ if (passwords > 0 || sealedInputs > 0 || sealedReveals > 0) {
39
+ this.log.info("expired sealed values deleted", { passwords, sealedInputs, sealedReveals });
38
40
  }
39
41
  }
40
42
  };
@@ -7,15 +7,8 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
7
7
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
8
8
  import { type InvitableRole, type Invitation, type InvitationStatus, InvitationsService } from "./invitations.service.js";
9
9
  import { type OrgContext } from "./org.guard.js";
10
+ import { InvitationCreateBody, InvitationIdParams } from "./orgs.schemas.js";
10
11
  import type { OrgRole } from "./roles.js";
11
- declare const CreateSchema: z.ZodObject<{
12
- role: z.ZodEnum<{
13
- admin: "admin";
14
- guest: "guest";
15
- member: "member";
16
- }>;
17
- expiresInHours: z.ZodOptional<z.ZodNumber>;
18
- }, z.core.$strip>;
19
12
  /** 组织邀请:组织内管理(`/api/v1/orgs/:orgId/invitations`)与凭令牌预览 / 接受(`/api/v1/invitations/:token`,公开)。 */
20
13
  export declare class InvitationsController {
21
14
  private readonly invitations;
@@ -24,7 +17,7 @@ export declare class InvitationsController {
24
17
  private readonly throttler;
25
18
  constructor(invitations: InvitationsService, sessions: SessionService, config: KernelConfigService, throttler: CredentialThrottler);
26
19
  /** 令牌只在此返回一次。 */
27
- create(principal: Principal, org: OrgContext, body: z.infer<typeof CreateSchema>): Promise<{
20
+ create(principal: Principal, org: OrgContext, body: z.infer<typeof InvitationCreateBody>): Promise<{
28
21
  invitation: Invitation;
29
22
  token: string;
30
23
  }>;
@@ -33,7 +26,7 @@ export declare class InvitationsController {
33
26
  status: InvitationStatus;
34
27
  })[];
35
28
  }>;
36
- revoke(principal: Principal, org: OrgContext, id: string): Promise<void>;
29
+ revoke(principal: Principal, org: OrgContext, { id }: z.infer<typeof InvitationIdParams>): Promise<void>;
37
30
  /** 公开预览:只给组织 id / 名称、角色与过期时间。 */
38
31
  preview(token: string): Promise<{
39
32
  org: {
@@ -55,4 +48,3 @@ export declare class InvitationsController {
55
48
  role: OrgRole;
56
49
  }>;
57
50
  }
58
- export {};
@@ -18,14 +18,13 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
18
18
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
19
19
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
20
20
  import { parseWithZod } from "../infra/validation/parse-with-zod.js";
21
- import { ZBody } from "../infra/validation/zod-params.js";
22
- import { INVITABLE_ROLES, InvitationsService, MAX_INVITATION_HOURS, } from "./invitations.service.js";
21
+ import { ZBody, ZParam } from "../infra/validation/zod-params.js";
22
+ import { InvitationsService, } from "./invitations.service.js";
23
23
  import { CurrentOrg, OrgAction } from "./org.guard.js";
24
- const CreateSchema = z.object({
25
- role: z.enum(INVITABLE_ROLES),
26
- expiresInHours: z.number().int().min(1).max(MAX_INVITATION_HOURS).optional(),
27
- });
28
- class InvitationCreateBody extends createZodDto(CreateSchema, "InvitationCreateBody") {
24
+ import { InvitationCreateBody, InvitationIdParams } from "./orgs.schemas.js";
25
+ class InvitationCreateBodyDto extends createZodDto(InvitationCreateBody, "InvitationCreateBody") {
26
+ }
27
+ class InvitationIdParamsDto extends createZodDto(InvitationIdParams, "InvitationIdParams") {
29
28
  }
30
29
  /** Validated inside the handler, after the attempt is reserved (a signed-in principal sends none). */
31
30
  const SignupBody = z.object({
@@ -55,7 +54,7 @@ let InvitationsController = class InvitationsController {
55
54
  async list(org) {
56
55
  return { invitations: await this.invitations.list(org.orgId) };
57
56
  }
58
- async revoke(principal, org, id) {
57
+ async revoke(principal, org, { id }) {
59
58
  const p = requireUser(principal);
60
59
  await this.invitations.revoke(org.orgId, id, p.account.id, patTokenId(p));
61
60
  }
@@ -98,7 +97,7 @@ __decorate([
98
97
  OrgAction("org.invitations.manage"),
99
98
  __param(0, CurrentPrincipal()),
100
99
  __param(1, CurrentOrg()),
101
- __param(2, ZBody(InvitationCreateBody))
100
+ __param(2, ZBody(InvitationCreateBodyDto))
102
101
  ], InvitationsController.prototype, "create", null);
103
102
  __decorate([
104
103
  Get("orgs/:orgId/invitations"),
@@ -111,7 +110,7 @@ __decorate([
111
110
  HttpCode(204),
112
111
  __param(0, CurrentPrincipal()),
113
112
  __param(1, CurrentOrg()),
114
- __param(2, Param("id"))
113
+ __param(2, ZParam(InvitationIdParamsDto))
115
114
  ], InvitationsController.prototype, "revoke", null);
116
115
  __decorate([
117
116
  Get("invitations/:token"),
@@ -19,6 +19,11 @@ export type Invitation = {
19
19
  acceptedAt: Date | null;
20
20
  revokedAt: Date | null;
21
21
  };
22
+ /** Extras of {@link InvitationsService.create}. */
23
+ export interface InvitationCreateOptions {
24
+ auditDetail?: Record<string, unknown>;
25
+ inTransaction?: (invitation: Invitation, token: string) => Promise<void>;
26
+ }
22
27
  export type InvitationStatus = "pending" | "accepted" | "expired" | "revoked";
23
28
  export type AcceptAs = {
24
29
  accountId: string;
@@ -41,10 +46,15 @@ export declare class InvitationsService {
41
46
  private readonly members;
42
47
  private readonly orgLock;
43
48
  constructor(db: KernelDb, txHost: TransactionHost, accounts: AccountsService, members: MembersService, orgLock: OrgLock);
49
+ /**
50
+ * `opts.auditDetail` goes into the audit event (a write through the Platform tool says so);
51
+ * `opts.inTransaction` runs in the creation's transaction with the new invitation and its token
52
+ * (the Platform tool seals the token there for the person who approved the call).
53
+ */
44
54
  create(orgId: string, input: {
45
55
  role: InvitableRole;
46
56
  expiresInHours?: number | undefined;
47
- }, actorAccountId: string, actorTokenId?: string): Promise<{
57
+ }, actorAccountId: string, actorTokenId?: string, opts?: InvitationCreateOptions): Promise<{
48
58
  invitation: Invitation;
49
59
  token: string;
50
60
  }>;
@@ -53,7 +63,7 @@ export declare class InvitationsService {
53
63
  status: InvitationStatus;
54
64
  })[]>;
55
65
  /** 撤销;不属于该组织 → `invitation.invalid`;已接受 → `invitation.used`;已撤销则无操作。 */
56
- revoke(orgId: string, id: string, actorAccountId: string, actorTokenId?: string): Promise<void>;
66
+ revoke(orgId: string, id: string, actorAccountId: string, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<void>;
57
67
  preview(token: string): Promise<{
58
68
  org: {
59
69
  id: string;
@@ -57,7 +57,12 @@ let InvitationsService = class InvitationsService {
57
57
  this.members = members;
58
58
  this.orgLock = orgLock;
59
59
  }
60
- async create(orgId, input, actorAccountId, actorTokenId) {
60
+ /**
61
+ * `opts.auditDetail` goes into the audit event (a write through the Platform tool says so);
62
+ * `opts.inTransaction` runs in the creation's transaction with the new invitation and its token
63
+ * (the Platform tool seals the token there for the person who approved the call).
64
+ */
65
+ async create(orgId, input, actorAccountId, actorTokenId, opts = {}) {
61
66
  if (!INVITABLE_ROLES.includes(input.role)) {
62
67
  throw new ApiError("validation_failed", "Role cannot be invited");
63
68
  }
@@ -66,9 +71,9 @@ let InvitationsService = class InvitationsService {
66
71
  throw new ApiError("validation_failed", `expiresInHours must be an integer between 1 and ${MAX_INVITATION_HOURS}`);
67
72
  }
68
73
  const token = TOKEN_PREFIX + randomBytes(32).toString("base64url");
69
- return this.createIn(orgId, input.role, hours, token, actorAccountId, actorTokenId);
74
+ return this.createIn(orgId, input.role, hours, token, actorAccountId, actorTokenId, opts);
70
75
  }
71
- async createIn(orgId, role, hours, token, actorAccountId, actorTokenId) {
76
+ async createIn(orgId, role, hours, token, actorAccountId, actorTokenId, opts) {
72
77
  const input = { role };
73
78
  const { role: actorRole } = await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "org.invitations.manage");
74
79
  if (!roleAtLeast(actorRole, input.role))
@@ -91,9 +96,11 @@ let InvitationsService = class InvitationsService {
91
96
  orgId,
92
97
  action: "org.invitation.created",
93
98
  target: row.id,
94
- detail: { role: input.role, expiresAt: row.expires_at.toISOString() },
99
+ detail: { role: input.role, expiresAt: row.expires_at.toISOString(), ...opts.auditDetail },
95
100
  });
96
- return { invitation: toInvitation(row), token };
101
+ const invitation = toInvitation(row);
102
+ await opts.inTransaction?.(invitation, token);
103
+ return { invitation, token };
97
104
  }
98
105
  async list(orgId) {
99
106
  const rows = await this.db
@@ -116,7 +123,7 @@ let InvitationsService = class InvitationsService {
116
123
  });
117
124
  }
118
125
  /** 撤销;不属于该组织 → `invitation.invalid`;已接受 → `invitation.used`;已撤销则无操作。 */
119
- async revoke(orgId, id, actorAccountId, actorTokenId) {
126
+ async revoke(orgId, id, actorAccountId, actorTokenId, auditDetail) {
120
127
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "org.invitations.manage");
121
128
  const row = await this.db
122
129
  .selectFrom("invitations")
@@ -142,7 +149,7 @@ let InvitationsService = class InvitationsService {
142
149
  orgId,
143
150
  action: "org.invitation.revoked",
144
151
  target: id,
145
- detail: { role: row.role },
152
+ detail: { role: row.role, ...auditDetail },
146
153
  });
147
154
  }
148
155
  async preview(token) {
@@ -19,6 +19,16 @@ export interface Member {
19
19
  export declare function isAnonymousGuest(db: KernelSchemaDb, accountId: string): Promise<boolean>;
20
20
  /** 目标是匿名访客 → `409 member.anonymous_guest`。 */
21
21
  export declare function rejectAnonymousGuest(db: KernelSchemaDb, accountId: string): Promise<void>;
22
+ /** Extras of {@link MembersService.changeRole} and {@link MembersService.remove}. */
23
+ export interface MemberWriteOptions {
24
+ /** Goes into the audit event (a write through the Platform tool says so). */
25
+ auditDetail?: Record<string, unknown>;
26
+ /**
27
+ * Runs under the org row lock with the roles read there, before the service's own checks; throws
28
+ * to refuse (the Platform tool's limits, platform web parity spec §7.2).
29
+ */
30
+ guard?: (actorRole: OrgRole, targetRole: OrgRole) => void;
31
+ }
22
32
  /**
23
33
  * 成员服务。发起人只传账号 id,角色由服务在组织行锁内实时读取,调用方无法传入过期角色。所有写操作在事务内先 `SELECT … FROM orgs WHERE id = $1 FOR NO KEY UPDATE`,
24
34
  * 把同一组织的成员变更串行化(多副本下两个 owner 并发互相降级也恰好剩一个 owner)。
@@ -45,14 +55,14 @@ export declare class MembersService {
45
55
  * 发起人的角色在组织行锁内实时重读(spec 3.6 R5):已不是成员或低于 admin → `forbidden`。
46
56
  * 目标是匿名访客 → `member.anonymous_guest`。
47
57
  */
48
- changeRole(orgId: string, targetId: string, role: OrgRole, actorAccountId: string, actorTokenId?: string): Promise<void>;
58
+ changeRole(orgId: string, targetId: string, role: OrgRole, actorAccountId: string, actorTokenId?: string, opts?: MemberWriteOptions): Promise<void>;
49
59
  private changeRoleIn;
50
60
  /**
51
61
  * 移出成员:权限规则同 changeRole(移除 owner 须发起人是 owner);移除最后一个 owner → `org.last_owner`。
52
62
  * 走离职处理({@link Offboarding.offboard},原因 `removed`),与之同一事务;提交后写吊销标记、发布事件。
53
63
  * 匿名访客不能移出(`member.anonymous_guest`;不再需要匿名访问时把渠道连接改回绑定策略)。
54
64
  */
55
- remove(orgId: string, targetId: string, actorAccountId: string, actorTokenId?: string): Promise<void>;
65
+ remove(orgId: string, targetId: string, actorAccountId: string, actorTokenId?: string, opts?: MemberWriteOptions): Promise<void>;
56
66
  private removeIn;
57
67
  /** 主动离开:走离职处理(原因 `left`);最后一个 owner → `org.last_owner`。 */
58
68
  leave(orgId: string, accountId: string, actorTokenId?: string): Promise<void>;
@@ -111,12 +111,13 @@ let MembersService = class MembersService {
111
111
  * 发起人的角色在组织行锁内实时重读(spec 3.6 R5):已不是成员或低于 admin → `forbidden`。
112
112
  * 目标是匿名访客 → `member.anonymous_guest`。
113
113
  */
114
- async changeRole(orgId, targetId, role, actorAccountId, actorTokenId) {
115
- await this.changeRoleIn(orgId, targetId, role, actorAccountId, actorTokenId);
114
+ async changeRole(orgId, targetId, role, actorAccountId, actorTokenId, opts = {}) {
115
+ await this.changeRoleIn(orgId, targetId, role, actorAccountId, actorTokenId, opts);
116
116
  }
117
- async changeRoleIn(orgId, targetId, role, actorAccountId, actorTokenId) {
117
+ async changeRoleIn(orgId, targetId, role, actorAccountId, actorTokenId, opts) {
118
118
  const { role: actorRole } = await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "org.members.manage");
119
119
  const before = await this.requireMember(orgId, targetId);
120
+ opts.guard?.(actorRole, before);
120
121
  await rejectAnonymousGuest(this.db.db, targetId);
121
122
  if ((role === "owner" || before === "owner") && actorRole !== "owner") {
122
123
  throw new ApiError("org.owner_required", "Only an owner can change owner roles");
@@ -131,7 +132,7 @@ let MembersService = class MembersService {
131
132
  orgId,
132
133
  action: "org.member.role_changed",
133
134
  target: targetId,
134
- detail: { from: before, to: role },
135
+ detail: { from: before, to: role, ...opts.auditDetail },
135
136
  });
136
137
  }
137
138
  /**
@@ -139,16 +140,17 @@ let MembersService = class MembersService {
139
140
  * 走离职处理({@link Offboarding.offboard},原因 `removed`),与之同一事务;提交后写吊销标记、发布事件。
140
141
  * 匿名访客不能移出(`member.anonymous_guest`;不再需要匿名访问时把渠道连接改回绑定策略)。
141
142
  */
142
- async remove(orgId, targetId, actorAccountId, actorTokenId) {
143
- await this.removeIn(orgId, targetId, actorAccountId, actorTokenId);
143
+ async remove(orgId, targetId, actorAccountId, actorTokenId, opts = {}) {
144
+ await this.removeIn(orgId, targetId, actorAccountId, actorTokenId, opts);
144
145
  }
145
- async removeIn(orgId, targetId, actorAccountId, actorTokenId) {
146
+ async removeIn(orgId, targetId, actorAccountId, actorTokenId, opts) {
146
147
  // an unauthorized call is refused before it holds off the org's run writes
147
148
  await this.orgLock.precheck(orgId, actorAccountId, "org.members.manage");
148
149
  // offboarding: the org admission lock first (`Offboarding.offboard`)
149
150
  await this.orgLock.lockForRemoval(orgId);
150
151
  const { role: actorRole } = await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "org.members.manage");
151
152
  const before = await this.requireMember(orgId, targetId);
153
+ opts.guard?.(actorRole, before);
152
154
  await rejectAnonymousGuest(this.db.db, targetId);
153
155
  if (before === "owner" && actorRole !== "owner") {
154
156
  throw new ApiError("org.owner_required", "Only an owner can remove an owner");
@@ -162,7 +164,7 @@ let MembersService = class MembersService {
162
164
  orgId,
163
165
  action: "org.member.removed",
164
166
  target: targetId,
165
- detail: { role: before },
167
+ detail: { role: before, ...opts.auditDetail },
166
168
  });
167
169
  return res;
168
170
  }
@@ -4,9 +4,9 @@ import { type Principal } from "../identity/principal.js";
4
4
  import { type Member, MembersService } from "./members.service.js";
5
5
  import { OrgNetworkAllowances } from "./network-allowances.service.js";
6
6
  import { type OrgContext } from "./org.guard.js";
7
- import { type NetworkAllowanceView, OrgUpdateBody } from "./orgs.schemas.js";
7
+ import { MemberParams, MemberRoleBody, type NetworkAllowanceView, OrgUpdateBody } from "./orgs.schemas.js";
8
8
  import { type Org, OrgsService } from "./orgs.service.js";
9
- import { type OrgRole } from "./roles.js";
9
+ import type { OrgRole } from "./roles.js";
10
10
  declare const CreateSchema: z.ZodObject<{
11
11
  name: z.ZodString;
12
12
  slug: z.ZodOptional<z.ZodString>;
@@ -23,14 +23,6 @@ declare const ServiceTokenSchema: z.ZodObject<{
23
23
  }>;
24
24
  expiresAt: z.ZodOptional<z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>>;
25
25
  }, z.core.$strip>;
26
- declare const RoleSchema: z.ZodObject<{
27
- role: z.ZodEnum<{
28
- admin: "admin";
29
- guest: "guest";
30
- member: "member";
31
- owner: "owner";
32
- }>;
33
- }, z.core.$strip>;
34
26
  /** 组织与成员(`/api/v1/orgs`)。组织级路由由 `@OrgAction` + OrgGuard 每请求实时鉴权。 */
35
27
  export declare class OrgsController {
36
28
  private readonly orgs;
@@ -67,11 +59,11 @@ export declare class OrgsController {
67
59
  listNetworkAllowances(org: OrgContext): Promise<{
68
60
  allowances: NetworkAllowanceView[];
69
61
  }>;
70
- changeRole(principal: Principal, org: OrgContext, accountId: string, body: z.infer<typeof RoleSchema>): Promise<{
62
+ changeRole(principal: Principal, org: OrgContext, { accountId }: z.infer<typeof MemberParams>, body: z.infer<typeof MemberRoleBody>): Promise<{
71
63
  accountId: string;
72
64
  role: OrgRole;
73
65
  }>;
74
- removeMember(principal: Principal, org: OrgContext, accountId: string): Promise<void>;
66
+ removeMember(principal: Principal, org: OrgContext, { accountId }: z.infer<typeof MemberParams>): Promise<void>;
75
67
  createServiceToken(principal: Principal, org: OrgContext, body: z.infer<typeof ServiceTokenSchema>): Promise<{
76
68
  token: string;
77
69
  record: ApiTokenRecord;
@@ -13,13 +13,12 @@ import { ApiError } from "../errors.js";
13
13
  import { ApiTokenService, FutureIsoDate } from "../identity/api-tokens.js";
14
14
  import { CurrentPrincipal, patTokenId, requireUser, SessionOnly, } from "../identity/principal.js";
15
15
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
16
- import { ZBody } from "../infra/validation/zod-params.js";
16
+ import { ZBody, ZParam } from "../infra/validation/zod-params.js";
17
17
  import { MembersService } from "./members.service.js";
18
18
  import { OrgNetworkAllowances } from "./network-allowances.service.js";
19
19
  import { CurrentOrg, OrgAction } from "./org.guard.js";
20
- import { networkAllowanceView, OrgUpdateBody } from "./orgs.schemas.js";
20
+ import { MemberParams, MemberRoleBody, networkAllowanceView, OrgUpdateBody, } from "./orgs.schemas.js";
21
21
  import { OrgsService } from "./orgs.service.js";
22
- import { ORG_ROLES } from "./roles.js";
23
22
  const CreateSchema = z.object({
24
23
  name: z.string().min(1).max(100),
25
24
  slug: z.string().min(1).max(40).optional(),
@@ -38,8 +37,9 @@ const ServiceTokenSchema = z.object({
38
37
  });
39
38
  class ServiceTokenBody extends createZodDto(ServiceTokenSchema, "ServiceTokenBody") {
40
39
  }
41
- const RoleSchema = z.object({ role: z.enum(ORG_ROLES) });
42
- class MemberRoleBody extends createZodDto(RoleSchema, "MemberRoleBody") {
40
+ class MemberRoleBodyDto extends createZodDto(MemberRoleBody, "MemberRoleBody") {
41
+ }
42
+ class MemberParamsDto extends createZodDto(MemberParams, "MemberParams") {
43
43
  }
44
44
  /** 组织与成员(`/api/v1/orgs`)。组织级路由由 `@OrgAction` + OrgGuard 每请求实时鉴权。 */
45
45
  let OrgsController = class OrgsController {
@@ -94,12 +94,12 @@ let OrgsController = class OrgsController {
94
94
  async listNetworkAllowances(org) {
95
95
  return { allowances: (await this.allowances.list(org.orgId)).map(networkAllowanceView) };
96
96
  }
97
- async changeRole(principal, org, accountId, body) {
97
+ async changeRole(principal, org, { accountId }, body) {
98
98
  const p = requireUser(principal);
99
99
  await this.members.changeRole(org.orgId, accountId, body.role, p.account.id, patTokenId(p));
100
100
  return { accountId, role: body.role };
101
101
  }
102
- async removeMember(principal, org, accountId) {
102
+ async removeMember(principal, org, { accountId }) {
103
103
  const p = requireUser(principal);
104
104
  await this.members.remove(org.orgId, accountId, p.account.id, patTokenId(p));
105
105
  }
@@ -173,8 +173,8 @@ __decorate([
173
173
  OrgAction("org.members.manage"),
174
174
  __param(0, CurrentPrincipal()),
175
175
  __param(1, CurrentOrg()),
176
- __param(2, Param("accountId")),
177
- __param(3, ZBody(MemberRoleBody))
176
+ __param(2, ZParam(MemberParamsDto)),
177
+ __param(3, ZBody(MemberRoleBodyDto))
178
178
  ], OrgsController.prototype, "changeRole", null);
179
179
  __decorate([
180
180
  Delete(":orgId/members/:accountId"),
@@ -182,7 +182,7 @@ __decorate([
182
182
  HttpCode(204),
183
183
  __param(0, CurrentPrincipal()),
184
184
  __param(1, CurrentOrg()),
185
- __param(2, Param("accountId"))
185
+ __param(2, ZParam(MemberParamsDto))
186
186
  ], OrgsController.prototype, "removeMember", null);
187
187
  __decorate([
188
188
  Post(":orgId/service-tokens"),
@@ -4,6 +4,32 @@ export declare const OrgUpdateBody: z.ZodObject<{
4
4
  name: z.ZodOptional<z.ZodString>;
5
5
  slug: z.ZodOptional<z.ZodString>;
6
6
  }, z.core.$strip>;
7
+ /** `POST /api/v1/orgs/:orgId/invitations`: the role invited (never owner) and the link's life. */
8
+ export declare const InvitationCreateBody: z.ZodObject<{
9
+ role: z.ZodEnum<{
10
+ admin: "admin";
11
+ guest: "guest";
12
+ member: "member";
13
+ }>;
14
+ expiresInHours: z.ZodOptional<z.ZodNumber>;
15
+ }, z.core.$strip>;
16
+ /** `DELETE /api/v1/orgs/:orgId/invitations/:id`. */
17
+ export declare const InvitationIdParams: z.ZodObject<{
18
+ id: z.ZodString;
19
+ }, z.core.$strip>;
20
+ /** `PATCH` / `DELETE /api/v1/orgs/:orgId/members/:accountId`. */
21
+ export declare const MemberParams: z.ZodObject<{
22
+ accountId: z.ZodString;
23
+ }, z.core.$strip>;
24
+ /** `PATCH /api/v1/orgs/:orgId/members/:accountId`. */
25
+ export declare const MemberRoleBody: z.ZodObject<{
26
+ role: z.ZodEnum<{
27
+ admin: "admin";
28
+ guest: "guest";
29
+ member: "member";
30
+ owner: "owner";
31
+ }>;
32
+ }, z.core.$strip>;
7
33
  /** One org network allowance as the routes and Platform operations return it. */
8
34
  export interface NetworkAllowanceView {
9
35
  id: string;
@@ -1,9 +1,22 @@
1
1
  import { z } from "zod";
2
+ import { INVITABLE_ROLES, MAX_INVITATION_HOURS } from "./invitations.service.js";
3
+ import { ORG_ROLES } from "./roles.js";
2
4
  import { OrgSettingsPatchSchema } from "./settings.service.js";
3
5
  export const OrgUpdateBody = z.object({
4
6
  name: z.string().min(1).max(100).optional(),
5
7
  slug: z.string().min(1).max(40).optional(),
6
8
  });
9
+ /** `POST /api/v1/orgs/:orgId/invitations`: the role invited (never owner) and the link's life. */
10
+ export const InvitationCreateBody = z.object({
11
+ role: z.enum(INVITABLE_ROLES),
12
+ expiresInHours: z.number().int().min(1).max(MAX_INVITATION_HOURS).optional(),
13
+ });
14
+ /** `DELETE /api/v1/orgs/:orgId/invitations/:id`. */
15
+ export const InvitationIdParams = z.object({ id: z.string().min(1).max(100) });
16
+ /** `PATCH` / `DELETE /api/v1/orgs/:orgId/members/:accountId`. */
17
+ export const MemberParams = z.object({ accountId: z.string().min(1).max(100) });
18
+ /** `PATCH /api/v1/orgs/:orgId/members/:accountId`. */
19
+ export const MemberRoleBody = z.object({ role: z.enum(ORG_ROLES) });
7
20
  /** The view of a stored allowance: who added it stays in the audit log. */
8
21
  export function networkAllowanceView(a) {
9
22
  return { id: a.id, entry: a.entry, createdAt: a.createdAt };
@@ -13,6 +26,15 @@ export const ORG_ROUTES = [
13
26
  { route: "GET /api/v1/orgs/:orgId" },
14
27
  { route: "PATCH /api/v1/orgs/:orgId", body: OrgUpdateBody },
15
28
  { route: "GET /api/v1/orgs/:orgId/members" },
29
+ {
30
+ route: "PATCH /api/v1/orgs/:orgId/members/:accountId",
31
+ params: MemberParams,
32
+ body: MemberRoleBody,
33
+ },
34
+ { route: "DELETE /api/v1/orgs/:orgId/members/:accountId", params: MemberParams },
35
+ { route: "POST /api/v1/orgs/:orgId/invitations", body: InvitationCreateBody },
36
+ { route: "GET /api/v1/orgs/:orgId/invitations" },
37
+ { route: "DELETE /api/v1/orgs/:orgId/invitations/:id", params: InvitationIdParams },
16
38
  { route: "GET /api/v1/orgs/:orgId/network-allowances" },
17
39
  ];
18
40
  export const ORG_SETTINGS_ROUTES = [
@@ -0,0 +1,67 @@
1
+ import type { ConnectorAuth } from "../tools/credentials.js";
2
+ import type { PersonFieldSpec } from "./person-fields.js";
3
+ /**
4
+ * The person fields of a connector (platform web parity ruling R3). Credentials are not in a
5
+ * connector's `endpointSchema` (`endpointCredentialIssues` refuses them there), so the secret
6
+ * fields come from the auth method (`tools/credentials.ts`), by the paths of the create body:
7
+ * - `bearer` / `api_key`: `credential.token`;
8
+ * - `basic`: `credential.username`, `credential.password`;
9
+ * - `oauth_client`, `oauth_code` with a manual client: `client.clientSecret` (the client id stays
10
+ * a param; required for the client credentials flow, optional for a public code client).
11
+ *
12
+ * `none`, a dynamically registered client and custom `headers` have none: header names come from
13
+ * the auth preset (text an admin or the model wrote), never a card label, so header credentials
14
+ * are entered on the web. Labels are fixed, in both languages; every schema is a non-empty string.
15
+ */
16
+ export declare function connectorPersonFields(auth: ConnectorAuth, stored: ReadonlySet<string>): PersonFieldSpec[];
17
+ /**
18
+ * The credential value the create, credential and install bodies take, from the person's entered
19
+ * values (by the paths of {@link connectorPersonFields}, under `prefix`) and the model's client
20
+ * id: `{ token }`, `{ username, password }`, or the OAuth client `{ clientId, clientSecret? }`.
21
+ * Undefined when nothing was entered and no client given (the body then carries none).
22
+ */
23
+ export declare function connectorCredential(auth: ConnectorAuth, entered: Readonly<Record<string, string>>, clientId: string | undefined, prefix?: string): Record<string, string> | undefined;
24
+ /** A connector template whose connector a write creates: its id, card name and auth method. */
25
+ export interface TemplateTarget {
26
+ id: string;
27
+ /** The template's display name (from the plugin) in both languages, for the card labels. */
28
+ name: {
29
+ zh: string;
30
+ en: string;
31
+ };
32
+ auth: ConnectorAuth;
33
+ }
34
+ /**
35
+ * The person fields of connectors made from templates (the catalog install, the missing
36
+ * connectors of an installed plugin): each template's {@link connectorPersonFields} under
37
+ * `connectors.<templateId>.`, labelled `<template name>: <label>`.
38
+ */
39
+ export declare function templatePersonFields(templates: readonly TemplateTarget[]): PersonFieldSpec[];
40
+ /** The model's non-secret input of one template's connector (a Platform operation param). */
41
+ export interface TemplateParams {
42
+ name?: string | undefined;
43
+ slug?: string | undefined;
44
+ endpoint?: Record<string, unknown> | undefined;
45
+ client?: {
46
+ clientId: string;
47
+ } | undefined;
48
+ }
49
+ /**
50
+ * One template's connector input as the install and configure bodies take it
51
+ * (`CatalogConnectorInput`): the model's params with the person's entered values (under
52
+ * `connectors.<templateId>.`) as `credential` or the OAuth client's `clientSecret`.
53
+ */
54
+ export declare function templateConnectorInput(t: TemplateTarget, params: TemplateParams | undefined, entered: Readonly<Record<string, string>>): Record<string, unknown>;
55
+ /**
56
+ * Why a write cannot ask the person for a connector's credential on the card, or null: custom
57
+ * header credentials (their names come from the auth preset) are entered on the web.
58
+ */
59
+ export declare function headersWebOnly(auth: ConnectorAuth, where: string): string | null;
60
+ /**
61
+ * Why a write's OAuth client param does not fit the auth method, or null: an OAuth client the
62
+ * person enters a secret for (oauth_client, oauth_code with a manual client) needs its id in
63
+ * `client`; any other auth method takes no client (refused rather than ignored).
64
+ */
65
+ export declare function clientProblem(auth: ConnectorAuth, client: {
66
+ clientId: string;
67
+ } | undefined, where: string): string | null;