@segmentstream/ontology 0.120.0 → 0.121.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.
@@ -67,9 +67,10 @@ export interface PrincipalRolesSql {
67
67
  readonly unsafe: (text: string, args: ReadonlyArray<unknown>) => Effect.Effect<ReadonlyArray<Readonly<Record<string, unknown>>>, SqlError>;
68
68
  }
69
69
  /**
70
- * The principal of a user with their current roles. An active member holds `member` beside their
71
- * assigned roles, unless `signUp` created them: they hold exactly what sign-up and later grants
72
- * gave them. A service holds exactly the roles it was given.
70
+ * The principal of a user with their current roles: exactly the roles an invitation, a grant or
71
+ * sign-up gave them. While the ontology declares `member`, an active member also holds `member`
72
+ * and the implicit reporter beside their assigned roles, unless `signUp` created them. A service
73
+ * holds exactly the roles it was given.
73
74
  */
74
75
  export declare function rolesOf(ontology: Ontology, sql: PrincipalRolesSql, user: UserRow): Effect.Effect<Principal, SqlError>;
75
76
  /** Resolve a workspace-owned identity/session by user id, with current activity and roles. */
@@ -96,10 +97,16 @@ export declare function resolvePipelineWorker(ontology: Ontology, execution: Wor
96
97
  /** A keyless hook actor with only the workspace's opted-in role; deactivated actors stay inactive. */
97
98
  export declare function resolveHookService(ontology: Ontology, heldRole: string): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
98
99
  /**
99
- * A workflow user's permissions: what `member` and the workflow's role grant, as `check` verified.
100
- * A `*:*` of member's is spelled out per entity, so that it covers what a named grant covers and
101
- * never the pipeline worker's workload wildcard; `check` refuses a workflow role holding `*:*`. An
102
- * entity a wildcard covers only some verbs of, the user, is spelled out with those verbs.
100
+ * The roles a workflow's runs hold: exactly its declared role. While the ontology declares
101
+ * `member`, they also hold the implicit `member`.
102
+ */
103
+ export declare function workflowRoles(ontology: Ontology, role: string): ReadonlyArray<string>;
104
+ /**
105
+ * A workflow user's permissions: what the workflow's role grants (with the implicit `member`'s,
106
+ * while the ontology declares one), as `check` verified. A `*:*` of member's is spelled out per
107
+ * entity, so that it covers what a named grant covers and never the pipeline worker's workload
108
+ * wildcard; `check` refuses a workflow role holding `*:*`. An entity a wildcard covers only some
109
+ * verbs of, the user, is spelled out with those verbs.
103
110
  */
104
111
  export declare function workflowPermissions(ontology: Ontology, role: string): ReadonlyArray<string>;
105
112
  /**
@@ -209,6 +216,11 @@ export interface PrincipalsManifest {
209
216
  /** The deployed workflows, whose users this ontology resolves and reconciles. Absent reads as none. */
210
217
  readonly workflows?: ReadonlyArray<WorkflowManifest> | undefined;
211
218
  }
219
+ /**
220
+ * The role names a deployed manifest reserves, which listings of its members and API keys leave
221
+ * out: `member` and `feedback_reporter` while it has the built-in `member`, none otherwise.
222
+ */
223
+ export declare function implicitRoleNamesOf(manifest: PrincipalsManifest): ReadonlyArray<string>;
212
224
  /**
213
225
  * An ontology with only the built-in `User` and the manifest's roles, with their permissions: what
214
226
  * managing principals needs. The platform holds a deployed ontology's manifest, not its code, and
@@ -234,12 +246,20 @@ export interface ApiKeySummary {
234
246
  /** The key acts only for the member each request names, with that member's roles. */
235
247
  readonly delegation: boolean;
236
248
  }
249
+ /**
250
+ * The role names a listing leaves out of a member's or an API key's stored roles: those
251
+ * {@link implicitRoleNames} reserves, and while nobody says, the earlier `member` and
252
+ * `feedback_reporter`.
253
+ */
254
+ export interface StoredRolesListing {
255
+ readonly hiddenRoles?: ReadonlyArray<string>;
256
+ }
237
257
  /** Every API key, oldest first, revoked ones included. */
238
- export declare function listApiKeys(): Effect.Effect<ReadonlyArray<ApiKeySummary>, never, SqlClient.SqlClient>;
258
+ export declare function listApiKeys(listing?: StoredRolesListing): Effect.Effect<ReadonlyArray<ApiKeySummary>, never, SqlClient.SqlClient>;
239
259
  /** One API key by its id, or undefined. */
240
260
  export declare function findApiKey(input: {
241
261
  readonly id: string;
242
- }): Effect.Effect<ApiKeySummary | undefined, never, SqlClient.SqlClient>;
262
+ } & StoredRolesListing): Effect.Effect<ApiKeySummary | undefined, never, SqlClient.SqlClient>;
243
263
  /** Where a member stands: invited and not signed in yet, signed in, or deactivated. */
244
264
  export type MemberStatus = "invited" | "active" | "inactive";
245
265
  /** A member as the platform lists it: a person's `user`, with the roles assigned to it. */
@@ -269,7 +289,7 @@ export type MemberKey = {
269
289
  readonly email: string;
270
290
  };
271
291
  /** Every member, signed in or not, by email. */
272
- export declare function listMembers(): Effect.Effect<ReadonlyArray<MemberSummary>, never, SqlClient.SqlClient>;
292
+ export declare function listMembers(listing?: StoredRolesListing): Effect.Effect<ReadonlyArray<MemberSummary>, never, SqlClient.SqlClient>;
273
293
  /**
274
294
  * Whether an address can receive the app's sign-in code: a user holds it who has signed in with
275
295
  * Neon Auth before, as `checkSignIn` answers `code`. Neon Auth sends codes only to its existing
@@ -10,9 +10,9 @@ import { MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, toSnakeCase } from "../names.js";
10
10
  import { feedbackRoles } from "../feedback-config.js";
11
11
  import { buildManifest, signUpRolesOf, } from "../manifest.js";
12
12
  import { buildOntology } from "../ontology.js";
13
- import { EXPLICIT_GRANT_ENTITIES, permissionsOf, principalScopes, WILDCARD_ENTITY_VERBS, } from "../permissions.js";
13
+ import { DEFAULT_MEMBER_PERMISSIONS, EXPLICIT_GRANT_ENTITIES, permissionsOf, principalScopes, WILDCARD_ENTITY_VERBS, } from "../permissions.js";
14
14
  import { EMAIL_PATTERN } from "../property.js";
15
- import { role, roleEntries } from "../role.js";
15
+ import { implicitMemberOf, implicitRoleNames, isImplicitRole, role, roleEntries } from "../role.js";
16
16
  import { beginReplicationWrite } from "../replication/transaction.js";
17
17
  import { User } from "../user.js";
18
18
  import { MemberNotFound, PrincipalRejected, UnknownRole } from "./errors.js";
@@ -138,9 +138,10 @@ function storedRoles(sql, userId) {
138
138
  });
139
139
  }
140
140
  /**
141
- * The principal of a user with their current roles. An active member holds `member` beside their
142
- * assigned roles, unless `signUp` created them: they hold exactly what sign-up and later grants
143
- * gave them. A service holds exactly the roles it was given.
141
+ * The principal of a user with their current roles: exactly the roles an invitation, a grant or
142
+ * sign-up gave them. While the ontology declares `member`, an active member also holds `member`
143
+ * and the implicit reporter beside their assigned roles, unless `signUp` created them. A service
144
+ * holds exactly the roles it was given.
144
145
  */
145
146
  export function rolesOf(ontology, sql, user) {
146
147
  return principalState(ontology, sql, user).pipe(Effect.map((state) => state.principal));
@@ -149,20 +150,22 @@ export function rolesOf(ontology, sql, user) {
149
150
  function principalState(ontology, sql, user) {
150
151
  return Effect.gen(function* () {
151
152
  const stored = yield* storedRoles(sql, user.id);
152
- // Ignore forged or historical stored assignments: reporter authority is never persisted, and
153
- // the guests' role is never a user's.
154
- const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE && !isGuestRole(ontology, role));
155
- const roles = user.kind === "member" && stored.signedUp
156
- ? assigned.filter((role) => role !== MEMBER_ROLE)
157
- : user.kind === "member"
158
- ? [
153
+ // @legacy ontology.implicit-member
154
+ const implicit = implicitMemberOf(ontology.roles) !== undefined;
155
+ // Ignore forged or historical stored assignments: the implicit reporter's authority is never
156
+ // persisted, and the guests' role is never a user's.
157
+ const assigned = stored.roles.filter((role) => !isImplicitReporter(ontology, role) && !isGuestRole(ontology, role));
158
+ const roles = !implicit || user.kind !== "member"
159
+ ? assigned
160
+ : stored.signedUp
161
+ ? assigned.filter((role) => role !== MEMBER_ROLE)
162
+ : [
159
163
  MEMBER_ROLE,
160
164
  ...assigned.filter((role) => role !== MEMBER_ROLE),
161
- ...(ontology.roles.some((role) => role.name === FEEDBACK_REPORTER_ROLE)
165
+ ...(ontology.roles.some((role) => role.name === FEEDBACK_REPORTER_ROLE && isImplicitRole(role))
162
166
  ? [FEEDBACK_REPORTER_ROLE]
163
167
  : []),
164
- ]
165
- : assigned;
168
+ ];
166
169
  // A role the deployed ontology no longer declares grants nothing.
167
170
  return {
168
171
  principal: {
@@ -474,7 +477,7 @@ export function resolveHookService(ontology, heldRole) {
474
477
  const sql = yield* SqlClient.SqlClient;
475
478
  const configured = ontology.config.hooks?.role;
476
479
  if (configured === undefined ||
477
- heldRole === FEEDBACK_REPORTER_ROLE ||
480
+ isImplicitReporter(ontology, heldRole) ||
478
481
  toSnakeCase(configured) !== heldRole ||
479
482
  !ontology.roles.some((candidate) => candidate.name === heldRole)) {
480
483
  return yield* new PrincipalRejected({
@@ -538,16 +541,33 @@ export function resolveHookService(ontology, heldRole) {
538
541
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
539
542
  }
540
543
  /**
541
- * A workflow user's permissions: what `member` and the workflow's role grant, as `check` verified.
542
- * A `*:*` of member's is spelled out per entity, so that it covers what a named grant covers and
543
- * never the pipeline worker's workload wildcard; `check` refuses a workflow role holding `*:*`. An
544
- * entity a wildcard covers only some verbs of, the user, is spelled out with those verbs.
544
+ * Whether a role name is the implicit reporter, which only people hold, never a workflow, a hook or
545
+ * a stored assignment: `feedback_reporter`, while the ontology declares `member`.
546
+ */
547
+ function isImplicitReporter(ontology, role) {
548
+ // @legacy ontology.implicit-member
549
+ return (toSnakeCase(role) === FEEDBACK_REPORTER_ROLE && implicitMemberOf(ontology.roles) !== undefined);
550
+ }
551
+ /**
552
+ * The roles a workflow's runs hold: exactly its declared role. While the ontology declares
553
+ * `member`, they also hold the implicit `member`.
554
+ */
555
+ export function workflowRoles(ontology, role) {
556
+ // @legacy ontology.implicit-member
557
+ return implicitMemberOf(ontology.roles) === undefined ? [role] : [MEMBER_ROLE, role];
558
+ }
559
+ /**
560
+ * A workflow user's permissions: what the workflow's role grants (with the implicit `member`'s,
561
+ * while the ontology declares one), as `check` verified. A `*:*` of member's is spelled out per
562
+ * entity, so that it covers what a named grant covers and never the pipeline worker's workload
563
+ * wildcard; `check` refuses a workflow role holding `*:*`. An entity a wildcard covers only some
564
+ * verbs of, the user, is spelled out with those verbs.
545
565
  */
546
566
  export function workflowPermissions(ontology, role) {
547
- if (toSnakeCase(role) === FEEDBACK_REPORTER_ROLE) {
567
+ if (isImplicitReporter(ontology, role)) {
548
568
  return [];
549
569
  }
550
- return permissionsOf(ontology.roles, [MEMBER_ROLE, role]).flatMap((permission) => permission === "*:*"
570
+ return permissionsOf(ontology.roles, workflowRoles(ontology, role)).flatMap((permission) => permission === "*:*"
551
571
  ? ontology.entities
552
572
  .filter((candidate) => !EXPLICIT_GRANT_ENTITIES.has(candidate.name))
553
573
  .flatMap((candidate) => {
@@ -630,7 +650,7 @@ export function resolveWorkflowUser(ontology, input) {
630
650
  return Effect.gen(function* () {
631
651
  const sql = yield* SqlClient.SqlClient;
632
652
  const declared = ontology.workflows.find((candidate) => candidate.name === input.workflow);
633
- if (declared === undefined || toSnakeCase(declared.role) === FEEDBACK_REPORTER_ROLE) {
653
+ if (declared === undefined || isImplicitReporter(ontology, declared.role)) {
634
654
  return yield* new PrincipalRejected({
635
655
  reason: "unknown_workflow",
636
656
  message: "The serving ontology declares no such workflow.",
@@ -677,7 +697,7 @@ export function resolveWorkflowUser(ontology, input) {
677
697
  kind: "service",
678
698
  roles: [declared.role],
679
699
  permissions: workflowPermissions(ontology, declared.role),
680
- ...principalScopes(ontology.roles, [MEMBER_ROLE, declared.role]),
700
+ ...principalScopes(ontology.roles, workflowRoles(ontology, declared.role)),
681
701
  workflow: { name: declared.name, subject },
682
702
  };
683
703
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
@@ -841,7 +861,7 @@ export function revokeApiKey(input) {
841
861
  function writeUserRoles(ontology, sql, input) {
842
862
  return Effect.gen(function* () {
843
863
  const known = new Set(userRoleNames(ontology));
844
- const unknown = input.roles.find((role) => toSnakeCase(role) === FEEDBACK_REPORTER_ROLE || !known.has(role));
864
+ const unknown = input.roles.find((role) => isImplicitReporter(ontology, role) || !known.has(role));
845
865
  if (unknown !== undefined) {
846
866
  return yield* new UnknownRole({
847
867
  role: unknown,
@@ -922,6 +942,16 @@ function deployedUser(manifest) {
922
942
  };
923
943
  return entity(User.name, definition);
924
944
  }
945
+ /**
946
+ * The role names a deployed manifest reserves, which listings of its members and API keys leave
947
+ * out: `member` and `feedback_reporter` while it has the built-in `member`, none otherwise.
948
+ */
949
+ export function implicitRoleNamesOf(manifest) {
950
+ // @legacy ontology.implicit-member
951
+ return manifest.roles.some((candidate) => candidate.builtIn && candidate.name === MEMBER_ROLE)
952
+ ? [MEMBER_ROLE, FEEDBACK_REPORTER_ROLE]
953
+ : [];
954
+ }
925
955
  /**
926
956
  * An ontology with only the built-in `User` and the manifest's roles, with their permissions: what
927
957
  * managing principals needs. The platform holds a deployed ontology's manifest, not its code, and
@@ -942,9 +972,15 @@ export function principalsOntology(manifest) {
942
972
  description: candidate.description,
943
973
  permissions: roleEntries(candidate.permissions ?? [], candidate.scopes ?? []),
944
974
  })),
945
- ...(builtIn?.permissions === undefined
975
+ // @legacy ontology.implicit-member
976
+ // A manifest with the built-in member keeps it; a manifest without one builds in no role.
977
+ ...(builtIn === undefined
946
978
  ? {}
947
- : { member: { permissions: roleEntries(builtIn.permissions, builtIn.scopes ?? []) } }),
979
+ : {
980
+ member: {
981
+ permissions: roleEntries(builtIn.permissions ?? DEFAULT_MEMBER_PERMISSIONS, builtIn.scopes ?? []),
982
+ },
983
+ }),
948
984
  }, { checkPermissions: false, user: deployedUser(manifest) });
949
985
  // The workflows' roles were checked with the manifest; it carries them for their users.
950
986
  const roles =
@@ -976,7 +1012,14 @@ const ApiKeyRow = Schema.Struct({
976
1012
  delegation: Schema.Boolean,
977
1013
  });
978
1014
  const decodeApiKeyRow = Schema.decodeUnknownSync(ApiKeyRow);
979
- function apiKeySummary(raw) {
1015
+ // @legacy ontology.implicit-member
1016
+ // A caller that does not say lists as before: without `member` and `feedback_reporter`.
1017
+ const EARLIER_HIDDEN_ROLES = [MEMBER_ROLE, FEEDBACK_REPORTER_ROLE];
1018
+ function hiddenOf(listing) {
1019
+ const hidden = new Set(listing?.hiddenRoles ?? EARLIER_HIDDEN_ROLES);
1020
+ return (role) => hidden.has(role) || hidden.has(toSnakeCase(role));
1021
+ }
1022
+ function apiKeySummary(raw, hidden) {
980
1023
  const row = decodeApiKeyRow(raw);
981
1024
  return {
982
1025
  id: row.id,
@@ -985,7 +1028,7 @@ function apiKeySummary(raw) {
985
1028
  createdAt: row.created_at,
986
1029
  revokedAt: row.revoked_at ?? undefined,
987
1030
  user: { id: row.user_id, name: row.user_name, active: row.user_active },
988
- roles: row.roles.filter((assigned) => toSnakeCase(assigned) !== FEEDBACK_REPORTER_ROLE),
1031
+ roles: row.roles.filter((assigned) => !hidden(assigned)),
989
1032
  delegation: row.delegation,
990
1033
  };
991
1034
  }
@@ -1001,11 +1044,11 @@ const API_KEY_COLUMNS = `"k"."id"::text AS "id", "k"."key_id" AS "key_id", "k"."
1001
1044
  ROLES_OF_USER;
1002
1045
  const API_KEY_FROM = `FROM "${API_KEYS_TABLE}" AS "k" JOIN "${USER_TABLE}" AS "u" ON "u"."id" = "k"."user_id"`;
1003
1046
  /** Every API key, oldest first, revoked ones included. */
1004
- export function listApiKeys() {
1047
+ export function listApiKeys(listing) {
1005
1048
  return Effect.gen(function* () {
1006
1049
  const sql = yield* SqlClient.SqlClient;
1007
1050
  const rows = yield* sql.unsafe(`SELECT ${API_KEY_COLUMNS} ${API_KEY_FROM} ORDER BY "k"."created_at", "k"."id"`);
1008
- return rows.map(apiKeySummary);
1051
+ return rows.map((row) => apiKeySummary(row, hiddenOf(listing)));
1009
1052
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
1010
1053
  }
1011
1054
  /** One API key by its id, or undefined. */
@@ -1016,7 +1059,7 @@ export function findApiKey(input) {
1016
1059
  }
1017
1060
  const sql = yield* SqlClient.SqlClient;
1018
1061
  const [row] = yield* sql.unsafe(`SELECT ${API_KEY_COLUMNS} ${API_KEY_FROM} WHERE "k"."id" = $1::uuid`, [input.id]);
1019
- return row === undefined ? undefined : apiKeySummary(row);
1062
+ return row === undefined ? undefined : apiKeySummary(row, hiddenOf(input));
1020
1063
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
1021
1064
  }
1022
1065
  const MemberRow = Schema.Struct({
@@ -1044,7 +1087,7 @@ function memberStatus(row) {
1044
1087
  }
1045
1088
  return row.signed_in ? "active" : "invited";
1046
1089
  }
1047
- function memberSummary(raw) {
1090
+ function memberSummary(raw, hidden) {
1048
1091
  const row = decodeMemberRow(raw);
1049
1092
  return {
1050
1093
  id: row.id,
@@ -1062,7 +1105,7 @@ function memberSummary(raw) {
1062
1105
  }
1063
1106
  : {}),
1064
1107
  status: memberStatus(row),
1065
- roles: row.roles.filter((assigned) => assigned !== MEMBER_ROLE && toSnakeCase(assigned) !== FEEDBACK_REPORTER_ROLE),
1108
+ roles: row.roles.filter((assigned) => !hidden(assigned)),
1066
1109
  lastSignInAt: row.last_sign_in_at ?? undefined,
1067
1110
  };
1068
1111
  }
@@ -1125,12 +1168,12 @@ function memberColumns(sql) {
1125
1168
  }
1126
1169
  const MEMBER_FROM = `FROM "${USER_TABLE}" AS "u" WHERE "u"."kind" = 'member'`;
1127
1170
  /** Every member, signed in or not, by email. */
1128
- export function listMembers() {
1171
+ export function listMembers(listing) {
1129
1172
  return Effect.gen(function* () {
1130
1173
  const sql = yield* SqlClient.SqlClient;
1131
1174
  const columns = yield* memberColumns(sql);
1132
1175
  const rows = yield* sql.unsafe(`SELECT ${columns} ${MEMBER_FROM} ORDER BY "u"."email" NULLS LAST, "u"."id"`);
1133
- return rows.map(memberSummary);
1176
+ return rows.map((row) => memberSummary(row, hiddenOf(listing)));
1134
1177
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
1135
1178
  }
1136
1179
  /** Emails are stored lowercased, as sign-in links them. */
@@ -1224,7 +1267,7 @@ function lockUser(runtime, key) {
1224
1267
  })
1225
1268
  .pipe(Effect.map(([user]) => user));
1226
1269
  }
1227
- function readMember(sql, id) {
1270
+ function readMember(ontology, sql, id) {
1228
1271
  return Effect.gen(function* () {
1229
1272
  const columns = yield* memberColumns(sql);
1230
1273
  const [row] = yield* sql.unsafe(`SELECT ${columns} ${MEMBER_FROM} AND "u"."id" = $1::uuid`, [
@@ -1233,7 +1276,7 @@ function readMember(sql, id) {
1233
1276
  if (row === undefined) {
1234
1277
  return yield* Effect.die(new Error(`Member ${id} was written but cannot be read back.`));
1235
1278
  }
1236
- return memberSummary(row);
1279
+ return memberSummary(row, hiddenOf({ hiddenRoles: implicitRoleNames(ontology.roles) }));
1237
1280
  });
1238
1281
  }
1239
1282
  /**
@@ -1251,8 +1294,9 @@ export function updateMemberRoles(ontology, change) {
1251
1294
  const revoke = change.revoke === "all" ? "all" : [...new Set(change.revoke ?? [])];
1252
1295
  const declared = userRoleNames(ontology);
1253
1296
  // Refused before anything is read, whoever the member is.
1254
- yield* requireGrantable(declared, grant ?? []);
1255
- yield* refuseMember(revoke === "all" ? [] : revoke);
1297
+ const reserved = implicitRoleNames(ontology.roles);
1298
+ yield* requireGrantable(declared, grant ?? [], reserved);
1299
+ yield* refuseMember(revoke === "all" ? [] : revoke, reserved);
1256
1300
  // One call is one platform write: its rows share an action id, each under its own action.
1257
1301
  const actionId = randomUUID();
1258
1302
  const runtime = (action) => platformRuntime(ontology, sql, action, actionId);
@@ -1274,7 +1318,7 @@ export function updateMemberRoles(ontology, change) {
1274
1318
  name: change.name,
1275
1319
  roles: grant,
1276
1320
  });
1277
- return yield* readMember(sql, invited.id);
1321
+ return yield* readMember(ontology, sql, invited.id);
1278
1322
  }
1279
1323
  const userId = found.id;
1280
1324
  const granted = grant ?? [];
@@ -1288,7 +1332,7 @@ export function updateMemberRoles(ontology, change) {
1288
1332
  id: userId,
1289
1333
  roles: granted,
1290
1334
  });
1291
- return yield* readMember(sql, userId);
1335
+ return yield* readMember(ontology, sql, userId);
1292
1336
  }));
1293
1337
  // Two first grants to one email race to create the member; the loser finds it on retry.
1294
1338
  return yield* attempt.pipe(Effect.catchTag("Conflict", () => attempt), Effect.catchTag(["Conflict", "NotFound"], (error) => Effect.die(error)));
@@ -1328,7 +1372,7 @@ export function setMemberActive(ontology, input) {
1328
1372
  }
1329
1373
  const id = user.id;
1330
1374
  yield* runtime.members.setActive({ id, active: input.active });
1331
- return yield* readMember(sql, id);
1375
+ return yield* readMember(ontology, sql, id);
1332
1376
  }));
1333
1377
  }).pipe(Effect.catchTag("NotFound", (error) => Effect.die(error)), Effect.catchIf(isSqlError, (error) => Effect.die(error)));
1334
1378
  }
@@ -1372,7 +1416,7 @@ export function setMemberBlocked(ontology, input) {
1372
1416
  if (input.blocked) {
1373
1417
  yield* revokeMemberSessions(sql, input.id);
1374
1418
  }
1375
- return yield* readMember(sql, input.id);
1419
+ return yield* readMember(ontology, sql, input.id);
1376
1420
  }));
1377
1421
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
1378
1422
  }
@@ -33,7 +33,7 @@ function projectionSchema(entity, fields) {
33
33
  function readExpression(field, column) {
34
34
  switch (field.storage) {
35
35
  case "list":
36
- return `${userRolesExpression(column)}::text`;
36
+ return `${userRolesExpression(column, field.hiddenRoles ?? [])}::text`;
37
37
  case "blob":
38
38
  return (`(SELECT json_build_object('id', b.id::text, 'filename', b.filename, ` +
39
39
  `'contentType', b.content_type, 'size', b.size, 'createdAt', ` +
@@ -207,9 +207,8 @@ export function resolveAgentIdentity(ontology, sql, store, requested, context =
207
207
  // Everyone sign-up created is counted, whatever roles they hold later.
208
208
  const counted = signedUp ||
209
209
  // @legacy ontology.legacy-channel-admission
210
- (provisioned &&
211
- member.principal.roles.length === 1 &&
212
- member.principal.roles[0] === "member");
210
+ // An open channel's user is counted while they hold no role but the earlier `member`.
211
+ (provisioned && member.principal.roles.every((role) => role === "member"));
213
212
  if (contact && counted) {
214
213
  for (const [scope, subject, window] of [
215
214
  ["turnsPerMinute", identity.userId, "minute"],
@@ -233,6 +232,7 @@ export function resolveAgentIdentity(ontology, sql, store, requested, context =
233
232
  status: created ? "created" : "existing",
234
233
  member: { ...member, principal: { ...member.principal, authenticatedVia: input.provider } },
235
234
  provisioned,
235
+ counted,
236
236
  noticeDue: provisioned &&
237
237
  (identity.noticedAt === null ||
238
238
  (input.noticeVersion !== undefined && identity.noticeVersion !== input.noticeVersion) ||
@@ -14,6 +14,7 @@ import { attributed } from "./history.js";
14
14
  import { grantMemberRoles, inviteMember, queueSignInEmail, revokeMemberRoles, setMemberActive, } from "./member-writes.js";
15
15
  import { entityModel, ontologyModel } from "./model.js";
16
16
  import { loadRecord, notFound, readHistory, relatedCondition, runQuery, validateQuery, } from "./reads.js";
17
+ import { implicitRoleNames } from "../role.js";
17
18
  import { userRoleNames } from "./guests.js";
18
19
  import { createRecord, deleteRecord, linkRecords, unlinkRecords, updateRecord, upsertRecord, } from "./writes.js";
19
20
  import { readScopeOf } from "./where.js";
@@ -277,7 +278,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
277
278
  ? operation(scope)
278
279
  : Effect.die(new Error(`Sign-in identities change only through ${action}, never in another action.`));
279
280
  const declaredRoles = userRoleNames(ontology);
280
- const memberWrite = (operation) => write(User.name, (writeContext, entity) => operation({ ...writeContext, sql, roles: declaredRoles }, entity));
281
+ const memberWrite = (operation) => write(User.name, (writeContext, entity) => operation({ ...writeContext, sql, roles: declaredRoles, reserved: implicitRoleNames(ontology.roles) }, entity));
281
282
  const members = {
282
283
  grantRoles: (input) => memberWrite((context, entity) => grantMemberRoles(context, entity, input)).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error))),
283
284
  revokeRoles: (input) => memberWrite((context, entity) => revokeMemberRoles(context, entity, input)).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error))),
@@ -1,16 +1,17 @@
1
1
  /**
2
- * The built-in user's `roles`: the roles assigned to the user in `_user_roles`, sorted, without the
3
- * `member` every active member holds implicitly. It is the only `list` property, and has no column.
2
+ * The built-in user's `roles`: the roles assigned to the user in `_user_roles`, sorted, without
3
+ * the role names the ontology reserves (the implicit `member` while it declares one). It is the
4
+ * only `list` property, and has no column.
4
5
  */
5
6
  export declare const USER_ROLES_PROPERTY = "roles";
6
7
  /**
7
8
  * The roles of the user whose id is the SQL expression `userId`, as a JSON array: sorted, without
8
- * `member`, `[]` when none. As a subquery of the statement that reads the user, it is consistent
9
- * with the row it reads.
9
+ * the `hidden` names, `[]` when none. As a subquery of the statement that reads the user, it is
10
+ * consistent with the row it reads.
10
11
  */
11
- export declare function userRolesExpression(userId: string): string;
12
+ export declare function userRolesExpression(userId: string, hidden: ReadonlyArray<string>): string;
12
13
  /**
13
14
  * Whether the user whose id is the SQL expression `userId` is assigned one of the roles, given as
14
- * SQL expressions such as parameters. `member` is never listed, so it matches no user.
15
+ * SQL expressions such as parameters. A `hidden` name is never listed, so it matches no user.
15
16
  */
16
- export declare function userHoldsRoleCondition(userId: string, roles: ReadonlyArray<string>): string;
17
+ export declare function userHoldsRoleCondition(userId: string, roles: ReadonlyArray<string>, hidden: ReadonlyArray<string>): string;
@@ -1,32 +1,37 @@
1
1
  import { USER_ROLES_TABLE, quoteIdentifier, quoteLiteral } from "../migrate/storage.js";
2
- import { MEMBER_ROLE } from "../names.js";
3
2
  /**
4
- * The built-in user's `roles`: the roles assigned to the user in `_user_roles`, sorted, without the
5
- * `member` every active member holds implicitly. It is the only `list` property, and has no column.
3
+ * The built-in user's `roles`: the roles assigned to the user in `_user_roles`, sorted, without
4
+ * the role names the ontology reserves (the implicit `member` while it declares one). It is the
5
+ * only `list` property, and has no column.
6
6
  */
7
7
  export const USER_ROLES_PROPERTY = "roles";
8
8
  const ROLES = quoteIdentifier(USER_ROLES_TABLE);
9
9
  /** Unlikely to shadow an alias of the enclosing statement, whose aliases are `t0`, `t1`, `j0`… */
10
10
  const ASSIGNED = '"_assigned_role"';
11
- const NOT_MEMBER = `${ASSIGNED}."role" <> ${quoteLiteral(MEMBER_ROLE)}`;
11
+ /** The condition leaving out the reserved names; `TRUE` when the ontology reserves none. */
12
+ function notHidden(hidden) {
13
+ return hidden.length === 0
14
+ ? "TRUE"
15
+ : `${ASSIGNED}."role" NOT IN (${hidden.map((role) => quoteLiteral(role)).join(", ")})`;
16
+ }
12
17
  /**
13
18
  * The roles of the user whose id is the SQL expression `userId`, as a JSON array: sorted, without
14
- * `member`, `[]` when none. As a subquery of the statement that reads the user, it is consistent
15
- * with the row it reads.
19
+ * the `hidden` names, `[]` when none. As a subquery of the statement that reads the user, it is
20
+ * consistent with the row it reads.
16
21
  */
17
- export function userRolesExpression(userId) {
22
+ export function userRolesExpression(userId, hidden) {
18
23
  return (`COALESCE((SELECT json_agg(${ASSIGNED}."role" ORDER BY ${ASSIGNED}."role") ` +
19
- `FROM ${ROLES} AS ${ASSIGNED} WHERE ${ASSIGNED}."user_id" = ${userId} AND ${NOT_MEMBER}), ` +
20
- `'[]'::json)`);
24
+ `FROM ${ROLES} AS ${ASSIGNED} WHERE ${ASSIGNED}."user_id" = ${userId} ` +
25
+ `AND ${notHidden(hidden)}), '[]'::json)`);
21
26
  }
22
27
  /**
23
28
  * Whether the user whose id is the SQL expression `userId` is assigned one of the roles, given as
24
- * SQL expressions such as parameters. `member` is never listed, so it matches no user.
29
+ * SQL expressions such as parameters. A `hidden` name is never listed, so it matches no user.
25
30
  */
26
- export function userHoldsRoleCondition(userId, roles) {
31
+ export function userHoldsRoleCondition(userId, roles, hidden) {
27
32
  if (roles.length === 0) {
28
33
  return "FALSE";
29
34
  }
30
35
  return (`EXISTS (SELECT 1 FROM ${ROLES} AS ${ASSIGNED} WHERE ${ASSIGNED}."user_id" = ${userId} ` +
31
- `AND ${NOT_MEMBER} AND ${ASSIGNED}."role" IN (${roles.join(", ")}))`);
36
+ `AND ${notHidden(hidden)} AND ${ASSIGNED}."role" IN (${roles.join(", ")}))`);
32
37
  }
@@ -284,14 +284,14 @@ export function fieldFilter(field, condition) {
284
284
  * The conditions of a list filter, joined with AND. The only list, the user's `roles`, is an
285
285
  * `EXISTS` on the role assignments of the row whose id `column` holds.
286
286
  */
287
- function listCondition(params, column, filter) {
287
+ function listCondition(params, column, filter, hidden) {
288
288
  const bind = (value) => params.add(value, "text");
289
289
  const parts = [];
290
290
  if (filter.has !== undefined) {
291
- parts.push(userHoldsRoleCondition(column, [bind(filter.has)]));
291
+ parts.push(userHoldsRoleCondition(column, [bind(filter.has)], hidden));
292
292
  }
293
293
  if (filter.hasAny !== undefined) {
294
- parts.push(userHoldsRoleCondition(column, filter.hasAny.map(bind)));
294
+ parts.push(userHoldsRoleCondition(column, filter.hasAny.map(bind), hidden));
295
295
  }
296
296
  return and(parts);
297
297
  }
@@ -299,7 +299,7 @@ function listCondition(params, column, filter) {
299
299
  export function fieldCondition(params, column, field, condition) {
300
300
  const filter = fieldFilter(field, condition);
301
301
  if (field.storage === "list") {
302
- return listCondition(params, column, filter);
302
+ return listCondition(params, column, filter, field.hiddenRoles ?? []);
303
303
  }
304
304
  const bind = (value) => params.add(bindValue(field, value), field.sqlType);
305
305
  const parts = [];
@@ -206,6 +206,7 @@ function resolveChannelIdentity(store, agentTools) {
206
206
  status: resolution.status,
207
207
  ...memberForWire(resolution.member, agentTools),
208
208
  provisioned: resolution.provisioned,
209
+ counted: resolution.counted,
209
210
  notice_due: resolution.noticeDue,
210
211
  on_new_user_pending: resolution.onNewUserPending,
211
212
  ...(resolution.inbox === true ? { inbox: true } : {}),
@@ -33,6 +33,8 @@ export interface AgentTaskRoutesOptions {
33
33
  readonly engine: WorkflowEngine;
34
34
  /** The agent's own tools a caller holds, which the task's answer carries for its user. */
35
35
  readonly agentTools: AgentToolsOf;
36
+ /** Whether the ontology declares `member`, which the task's user then holds beside its role. */
37
+ readonly implicitMember: boolean;
36
38
  }
37
39
  /**
38
40
  * The routes of the tasks workflows hand the app's agent with `agentTask`. Both take only the
@@ -32,7 +32,7 @@ function json(body, status = 200) {
32
32
  * as, from the ontology's records, never from the agent's request: their roles, and in
33
33
  * `agent_tools` the agent's own tools those roles grant.
34
34
  */
35
- function currentTask(backend, { task, principal }, agentTools) {
35
+ function currentTask(backend, { task, principal }, options) {
36
36
  return Effect.gen(function* () {
37
37
  const user = yield* backend
38
38
  .get({ entity: "user", id: principal.id })
@@ -45,8 +45,11 @@ function currentTask(backend, { task, principal }, agentTools) {
45
45
  principal: {
46
46
  id: principal.id,
47
47
  name: typeof user?.name === "string" ? user.name : task.workflow,
48
- roles: [...new Set([...principal.roles, MEMBER_ROLE])],
49
- agent_tools: agentTools(principal),
48
+ // @legacy ontology.implicit-member
49
+ roles: options.implicitMember
50
+ ? [...new Set([...principal.roles, MEMBER_ROLE])]
51
+ : principal.roles,
52
+ agent_tools: options.agentTools(principal),
50
53
  },
51
54
  });
52
55
  });
@@ -151,7 +154,7 @@ export function agentTasksLayer(options) {
151
154
  ? refused(caller.detail)
152
155
  : yield* answer(request, caller);
153
156
  });
154
- yield* router.add("GET", AGENT_TASK_PATH, asTask((_, live) => currentTask(backend, live, options.agentTools)));
157
+ yield* router.add("GET", AGENT_TASK_PATH, asTask((_, live) => currentTask(backend, live, options)));
155
158
  yield* router.add("POST", AGENT_TASK_RESULT_PATH, asTask((request, live) => reportResult(store, options.engine, request, live)));
156
159
  }));
157
160
  }
@@ -516,6 +516,11 @@ export type AgentResolution = {
516
516
  readonly status: "existing" | "created";
517
517
  readonly member: AgentMember;
518
518
  readonly provisioned: boolean;
519
+ /**
520
+ * The person's turns count against the per-sender and workspace turn limits: everyone sign-up
521
+ * created, and an open channel's user while they hold no role but the earlier `member`.
522
+ */
523
+ readonly counted: boolean;
519
524
  readonly noticeDue: boolean;
520
525
  readonly onNewUserPending: boolean;
521
526
  /**
@@ -12,6 +12,7 @@ import { parsePageCatalog } from "../navigation-catalog.js";
12
12
  import { guestOf, signUpOriginsOf, signUpRolesOf } from "../manifest.js";
13
13
  import { isAllowed } from "../permissions.js";
14
14
  import { agentToolsFor } from "../runtime/guests.js";
15
+ import { implicitMemberOf } from "../role.js";
15
16
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
16
17
  import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-links.js";
17
18
  import { memberFileRoutes } from "./member-file-routes.js";
@@ -432,6 +433,7 @@ export function createOntologyService(ontology, config) {
432
433
  workspaceId: config.workspaceId,
433
434
  engine: config.workflowEngine ?? vercelWorkflowEngine,
434
435
  agentTools,
436
+ implicitMember: implicitMemberOf(ontology.roles) !== undefined,
435
437
  });
436
438
  const attachments = preview
437
439
  ? Layer.empty