@segmentstream/ontology 0.94.1 → 0.96.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 (58) hide show
  1. package/README.md +52 -7
  2. package/dist/analyze.d.ts +15 -3
  3. package/dist/analyze.js +217 -5
  4. package/dist/authoring.js +3 -0
  5. package/dist/index.d.ts +8 -8
  6. package/dist/index.js +5 -5
  7. package/dist/manifest-compatibility.d.ts +7 -0
  8. package/dist/manifest-compatibility.js +12 -0
  9. package/dist/manifest.d.ts +102 -18
  10. package/dist/manifest.js +41 -2
  11. package/dist/migrate/apply.d.ts +3 -2
  12. package/dist/migrate/apply.js +11 -3
  13. package/dist/migrate/model.d.ts +60 -12
  14. package/dist/migrate/plan.js +9 -1
  15. package/dist/migrate/storage.d.ts +7 -0
  16. package/dist/migrate/storage.js +24 -12
  17. package/dist/ontology.d.ts +2 -2
  18. package/dist/permissions.d.ts +9 -0
  19. package/dist/permissions.js +8 -0
  20. package/dist/runtime/channel-identity-admin.d.ts +41 -0
  21. package/dist/runtime/channel-identity-admin.js +223 -0
  22. package/dist/runtime/generated-actions.d.ts +2 -1
  23. package/dist/runtime/generated-actions.js +71 -3
  24. package/dist/runtime/member-tables.d.ts +7 -2
  25. package/dist/runtime/member-tables.js +18 -3
  26. package/dist/runtime/new-user-hook.d.ts +11 -1
  27. package/dist/runtime/new-user-hook.js +69 -29
  28. package/dist/runtime/pipeline.d.ts +2 -0
  29. package/dist/runtime/pipeline.js +11 -3
  30. package/dist/runtime/principals.d.ts +37 -3
  31. package/dist/runtime/principals.js +140 -36
  32. package/dist/runtime/resolve-agent-identity.js +43 -12
  33. package/dist/runtime/service-binding.js +11 -4
  34. package/dist/runtime/sql-runtime.d.ts +14 -1
  35. package/dist/runtime/sql-runtime.js +9 -0
  36. package/dist/runtime/user-identities.d.ts +5 -3
  37. package/dist/runtime/user-identities.js +9 -4
  38. package/dist/runtime/user-identity-sql.d.ts +4 -1
  39. package/dist/runtime/user-identity-sql.js +5 -2
  40. package/dist/runtime-source.d.ts +6 -0
  41. package/dist/runtime-source.js +11 -0
  42. package/dist/service/agent/attachments.js +4 -0
  43. package/dist/service/agent/authentication.d.ts +74 -2
  44. package/dist/service/agent/authentication.js +93 -11
  45. package/dist/service/agent/files.js +8 -1
  46. package/dist/service/agent/server.js +13 -2
  47. package/dist/service/authentication.js +58 -2
  48. package/dist/service/caller-context.d.ts +16 -0
  49. package/dist/service/chat/envelope.d.ts +20 -2
  50. package/dist/service/chat/envelope.js +10 -0
  51. package/dist/service/runtime-contract.d.ts +9 -0
  52. package/dist/service/schemas.d.ts +12 -0
  53. package/dist/sign-in.d.ts +32 -1
  54. package/dist/sign-in.js +12 -1
  55. package/dist/storage/attachments.d.ts +11 -0
  56. package/dist/user-identity.d.ts +14 -5
  57. package/dist/user-identity.js +25 -5
  58. package/package.json +1 -1
@@ -1,37 +1,77 @@
1
1
  import { Cause, Effect } from "effect";
2
2
  import { SqlClient } from "effect/unstable/sql";
3
3
  import { CHANNEL_USERS_TABLE } from "../migrate/storage.js";
4
+ import { FEEDBACK_REPORTER_ROLE, MEMBER_ROLE } from "../names.js";
4
5
  import { permissionsOf, principalScopes } from "../permissions.js";
6
+ import { signUpPending } from "./member-tables.js";
5
7
  import { runAction } from "./pipeline.js";
6
- /** Runs after admission commits, before a model turn or channel-app session. True means retry pending. */
8
+ /**
9
+ * Runs after admission commits, before a model turn or app session. True means retry pending.
10
+ * A user `signUp` created runs `onSignUp` with the roles they hold; a user an open
11
+ * `signIn.channels` created runs `onNewUser` with only `member`. Workload authority never applies.
12
+ */
7
13
  export function runNewUserHook(ontology, sql, principal) {
8
- const hook = ontology.signIn.onNewUser;
9
- if (hook === undefined) {
10
- return Effect.succeed(false);
14
+ return Effect.gen(function* () {
15
+ const [lifecycle] = yield* sql.unsafe(`SELECT to_jsonb("c") ->> 'signed_up' AS "signed_up" FROM "${CHANNEL_USERS_TABLE}" AS "c"
16
+ WHERE "c"."user_id" = $1::uuid`, [principal.id]);
17
+ const signedUp = lifecycle?.signed_up === "true";
18
+ // @legacy ontology.legacy-channel-admission
19
+ const hook = signedUp ? ontology.signIn.onSignUp : ontology.signIn.onNewUser;
20
+ if (hook === undefined) {
21
+ return false;
22
+ }
23
+ const declared = new Set(ontology.roles.map((candidate) => candidate.name));
24
+ const roles = signedUp
25
+ ? principal.roles.filter((role) => declared.has(role) && role !== MEMBER_ROLE && role !== FEEDBACK_REPORTER_ROLE)
26
+ : [MEMBER_ROLE];
27
+ const [entity, action] = hook.split(":");
28
+ yield* runAction(ontology, {
29
+ entity: entity,
30
+ action: action,
31
+ input: {},
32
+ principal: {
33
+ id: principal.id,
34
+ kind: "member",
35
+ ...(principal.authenticatedVia === undefined
36
+ ? {}
37
+ : { authenticatedVia: principal.authenticatedVia }),
38
+ roles,
39
+ permissions: permissionsOf(ontology.roles, roles),
40
+ ...principalScopes(ontology.roles, roles),
41
+ },
42
+ options: { newUserHook: true, ...(signedUp ? { signUpHook: true } : {}) },
43
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.flatMap((outcome) => outcome.validation.ok ? Effect.void : Effect.die(new Error("Invalid onboarding input."))), Effect.catchCause((cause) => Effect.logWarning("ontology.channel.on_new_user_pending", Cause.pretty(cause)
44
+ .replace(/(postgres(?:ql)?:\/\/[^:\s]+:)[^@\s]+@/gi, "$1[redacted]@")
45
+ .replace(/Bearer\s+[^\s"']+/gi, "Bearer [redacted]")
46
+ .replace(/\b(?:sso|ssr|ssc|sss|ssk|ssw)_[A-Za-z0-9_-]+/g, "[redacted]")).pipe(Effect.annotateLogs({
47
+ operation: "ontology.channel.on_new_user",
48
+ userId: principal.id,
49
+ action: hook,
50
+ }))));
51
+ const [stored] = yield* sql.unsafe(`SELECT "on_new_user_completed_at" IS NULL AS "pending" FROM "${CHANNEL_USERS_TABLE}" AS "c"
52
+ WHERE "c"."user_id" = $1::uuid
53
+ AND (COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true'
54
+ OR "c"."created_via" NOT IN ('invite', 'email'))`, [principal.id]);
55
+ return stored?.pending ?? false;
56
+ }).pipe(Effect.orDie);
57
+ }
58
+ /**
59
+ * The federation store, running a signed-up user's pending `onSignUp` once they enroll through a
60
+ * SegmentStream account and on each later federated request until it completes.
61
+ */
62
+ export function withSignUpOnboarding(ontology, sql, store) {
63
+ if (ontology.signIn.onSignUp === undefined) {
64
+ return store;
11
65
  }
12
- const [entity, action] = hook.split(":");
13
- return runAction(ontology, {
14
- entity: entity,
15
- action: action,
16
- input: {},
17
- principal: {
18
- id: principal.id,
19
- kind: "member",
20
- ...(principal.authenticatedVia === undefined
21
- ? {}
22
- : { authenticatedVia: principal.authenticatedVia }),
23
- roles: ["member"],
24
- permissions: permissionsOf(ontology.roles, ["member"]),
25
- ...principalScopes(ontology.roles, ["member"]),
26
- },
27
- options: { newUserHook: true },
28
- }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.flatMap((outcome) => outcome.validation.ok ? Effect.void : Effect.die(new Error("Invalid onNewUser input."))), Effect.catchCause((cause) => Effect.logWarning("ontology.channel.on_new_user_pending", Cause.pretty(cause)
29
- .replace(/(postgres(?:ql)?:\/\/[^:\s]+:)[^@\s]+@/gi, "$1[redacted]@")
30
- .replace(/Bearer\s+[^\s"']+/gi, "Bearer [redacted]")
31
- .replace(/\b(?:sso|ssr|ssc|sss|ssk|ssw)_[A-Za-z0-9_-]+/g, "[redacted]")).pipe(Effect.annotateLogs({
32
- operation: "ontology.channel.on_new_user",
33
- userId: principal.id,
34
- action: hook,
35
- }))), Effect.andThen(sql.unsafe(`SELECT "on_new_user_completed_at" IS NULL AS "pending" FROM "${CHANNEL_USERS_TABLE}"
36
- WHERE "user_id" = $1::uuid AND "created_via" NOT IN ('invite', 'email')`, [principal.id])), Effect.map(([stored]) => stored?.pending ?? false), Effect.orDie);
66
+ const onboard = (principal) => principal === undefined || principal.kind !== "member"
67
+ ? Effect.succeed(principal)
68
+ : signUpPending(sql, principal.id).pipe(Effect.flatMap((pending) => pending ? runNewUserHook(ontology, sql, principal) : Effect.void), Effect.as(principal), Effect.orDie);
69
+ return {
70
+ ...store,
71
+ identity: (issuer, subject) => store.identity(issuer, subject).pipe(Effect.flatMap(onboard)),
72
+ principal: (id) => store.principal(id).pipe(Effect.flatMap(onboard)),
73
+ ...(store.enroll === undefined
74
+ ? {}
75
+ : { enroll: (claims) => store.enroll(claims).pipe(Effect.flatMap(onboard)) }),
76
+ };
37
77
  }
@@ -43,6 +43,8 @@ export interface ActionRequest<R = never> {
43
43
  readonly createIntent?: string;
44
44
  /** Internal channel lifecycle execution; marker commits atomically with the handler. */
45
45
  readonly newUserHook?: true;
46
+ /** With `newUserHook`: the hook is `onSignUp`, for a user sign-up created. */
47
+ readonly signUpHook?: true;
46
48
  /**
47
49
  * Describe what a person confirms before the action runs, in the chat's language, with the
48
50
  * action's `confirm`: decode the input, check the permission, and answer with the confirmation,
@@ -190,8 +190,11 @@ export function runAction(ontology, request) {
190
190
  yield* Effect.sync(() => requireDeploymentCapability(deployment, "connections"));
191
191
  }
192
192
  const newUserHook = request.options?.newUserHook === true;
193
+ const qualifiedHook = `${request.entity}:${request.action}`;
194
+ const signUpHook = newUserHook && request.options?.signUpHook === true;
193
195
  if (newUserHook &&
194
- (ontology.signIn.onNewUser !== `${request.entity}:${request.action}` ||
196
+ // @legacy ontology.legacy-channel-admission
197
+ ((signUpHook ? ontology.signIn.onSignUp : ontology.signIn.onNewUser) !== qualifiedHook ||
195
198
  action.prepare !== undefined ||
196
199
  action.connections.length > 0 ||
197
200
  action.hints?.idempotent !== true ||
@@ -416,9 +419,14 @@ export function runAction(ontology, request) {
416
419
  yield* sql.unsafe(`SELECT "id" FROM "${USER_TABLE}" WHERE "id" = $1::uuid FOR UPDATE`, [
417
420
  request.principal.id,
418
421
  ]);
422
+ // `onSignUp` runs for users sign-up created; `onNewUser` for those an open
423
+ // `signIn.channels` created.
419
424
  const [pending] = yield* sql.unsafe(`SELECT 1 FROM "${CHANNEL_USERS_TABLE}" c JOIN "${USER_TABLE}" u ON u."id" = c."user_id"
420
- WHERE c."user_id" = $1::uuid AND c."created_via" NOT IN ('invite', 'email')
421
- AND c."blocked_at" IS NULL AND c."on_new_user_completed_at" IS NULL AND u."active" FOR UPDATE OF c`, [request.principal.id]);
425
+ WHERE c."user_id" = $1::uuid
426
+ AND CASE WHEN $2 THEN COALESCE(to_jsonb(c) ->> 'signed_up', 'false') = 'true'
427
+ ELSE COALESCE(to_jsonb(c) ->> 'signed_up', 'false') <> 'true'
428
+ AND c."created_via" NOT IN ('invite', 'email') END
429
+ AND c."blocked_at" IS NULL AND c."on_new_user_completed_at" IS NULL AND u."active" FOR UPDATE OF c`, [request.principal.id, signUpHook]);
422
430
  if (pending === undefined) {
423
431
  return null;
424
432
  }
@@ -66,6 +66,11 @@ export declare const MEMBER_HISTORY_ACTIONS: {
66
66
  export interface PrincipalRolesSql {
67
67
  readonly unsafe: (text: string, args: ReadonlyArray<unknown>) => Effect.Effect<ReadonlyArray<Readonly<Record<string, unknown>>>, SqlError>;
68
68
  }
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.
73
+ */
69
74
  export declare function rolesOf(ontology: Ontology, sql: PrincipalRolesSql, user: UserRow): Effect.Effect<Principal, SqlError>;
70
75
  /** Resolve a workspace-owned identity/session by user id, with current activity and roles. */
71
76
  export declare function resolvePrincipalById(ontology: Ontology, sql: SqlClient.SqlClient, id: string): Effect.Effect<Principal, SqlError | PrincipalRejected, never>;
@@ -78,6 +83,14 @@ export declare function resolvePrincipalById(ontology: Ontology, sql: SqlClient.
78
83
  * deferred to a later request instead of delaying authentication. Inactive users are rejected.
79
84
  */
80
85
  export declare function resolvePrincipalByIdentity(ontology: Ontology, claims: IdentityClaims): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
86
+ /**
87
+ * {@link resolvePrincipalByIdentity}, and whether the user email sign-up created still waits for
88
+ * `onSignUp`. The caller runs it once nothing else holds a transaction; see `runNewUserHook`.
89
+ */
90
+ export declare function resolveSignInState(ontology: Ontology, claims: IdentityClaims): Effect.Effect<{
91
+ readonly principal: Principal;
92
+ readonly signUpPending: boolean;
93
+ }, PrincipalRejected, SqlClient.SqlClient>;
81
94
  /** Resolve the workspace's stable keyless pipeline service, without customer roles or sign-in. */
82
95
  export declare function resolvePipelineWorker(ontology: Ontology, execution: WorkloadExecution): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
83
96
  /** A keyless hook actor with only the workspace's opted-in role; deactivated actors stay inactive. */
@@ -111,11 +124,22 @@ export declare function resolveWorkflowUser(ontology: Ontology, input: {
111
124
  export declare function reconcileWorkflowUsers(ontology: Ontology, input: {
112
125
  readonly workspaceId: string;
113
126
  }): Effect.Effect<void, SqlError, SqlClient.SqlClient>;
127
+ /**
128
+ * An API key, verified: its user's principal, and whether it acts with `delegation`, only for the
129
+ * member each request names, instead of with that principal's roles.
130
+ */
131
+ export interface ApiKeyCredential {
132
+ readonly principal: Principal;
133
+ readonly delegation: boolean;
134
+ }
114
135
  /**
115
136
  * The principal of an API key, with the permissions its roles have in the ontology. Unknown and
116
- * revoked keys and inactive users are rejected.
137
+ * revoked keys and inactive users are rejected. A key with delegation resolves to its user too: the
138
+ * service authenticates its requests as the member they name, and refuses them otherwise.
117
139
  */
118
140
  export declare function resolvePrincipalByApiKey(ontology: Ontology, key: string): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
141
+ /** An API key's principal and whether it acts with delegation; see {@link resolvePrincipalByApiKey}. */
142
+ export declare function resolveApiKeyCredential(ontology: Ontology, key: string): Effect.Effect<ApiKeyCredential, PrincipalRejected, SqlClient.SqlClient>;
119
143
  /**
120
144
  * A member by user id, with the roles they hold now: whom an OAuth grant acts for. `undefined` for
121
145
  * an unknown user, a service and an inactive member.
@@ -126,10 +150,15 @@ export interface CreatedApiKey {
126
150
  /** The key itself. It is not stored and cannot be shown again. */
127
151
  readonly key: string;
128
152
  }
129
- /** Issues an API key for a user. */
153
+ /**
154
+ * Issues an API key for a user. With `delegation` the key acts only for the member each request
155
+ * names; the column is written only then, so that keys without it can still be issued on a
156
+ * database an earlier SDK migrated.
157
+ */
130
158
  export declare function createApiKey(input: {
131
159
  readonly userId: string;
132
160
  readonly label: string;
161
+ readonly delegation?: boolean;
133
162
  }): Effect.Effect<CreatedApiKey, never, SqlClient.SqlClient>;
134
163
  /** Revokes an API key. Revoking it again changes nothing. */
135
164
  export declare function revokeApiKey(input: {
@@ -142,12 +171,15 @@ export declare function setUserRoles(ontology: Ontology, input: {
142
171
  }): Effect.Effect<void, UnknownRole, SqlClient.SqlClient>;
143
172
  /**
144
173
  * Creates a service user with roles and a first API key, as the app or the CLI does for the
145
- * website's intake key.
174
+ * website's intake key. With `delegation` the service holds no role and its key acts only for the
175
+ * member each request names, as an external agent the workspace trusts does: roles and delegation
176
+ * never come together, so that such a key has no authority of its own.
146
177
  */
147
178
  export declare function createServiceUser(ontology: Ontology, input: {
148
179
  readonly name: string;
149
180
  readonly roles: ReadonlyArray<string>;
150
181
  readonly keyLabel: string;
182
+ readonly delegation?: boolean;
151
183
  }): Effect.Effect<{
152
184
  readonly user: StoredRecord;
153
185
  readonly apiKey: CreatedApiKey;
@@ -199,6 +231,8 @@ export interface ApiKeySummary {
199
231
  readonly active: boolean;
200
232
  };
201
233
  readonly roles: ReadonlyArray<string>;
234
+ /** The key acts only for the member each request names, with that member's roles. */
235
+ readonly delegation: boolean;
202
236
  }
203
237
  /** Every API key, oldest first, revoked ones included. */
204
238
  export declare function listApiKeys(): Effect.Effect<ReadonlyArray<ApiKeySummary>, never, SqlClient.SqlClient>;
@@ -8,7 +8,7 @@ import { entity, } from "../entity.js";
8
8
  import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE, API_KEYS_TABLE, USER_ROLES_TABLE, USER_TABLE, } from "../migrate/storage.js";
9
9
  import { MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, toSnakeCase } from "../names.js";
10
10
  import { feedbackRoles } from "../feedback-config.js";
11
- import { buildManifest } from "../manifest.js";
11
+ import { buildManifest, signUpRolesOf, } from "../manifest.js";
12
12
  import { buildOntology } from "../ontology.js";
13
13
  import { EXPLICIT_GRANT_ENTITIES, permissionsOf, principalScopes, WILDCARD_ENTITY_VERBS, } from "../permissions.js";
14
14
  import { EMAIL_PATTERN } from "../property.js";
@@ -97,34 +97,87 @@ export const MEMBER_HISTORY_ACTIONS = {
97
97
  deactivate: "user.deactivate",
98
98
  reactivate: "user.reactivate",
99
99
  };
100
+ /** Clients whose database has `_channel_users`. It is never dropped, so only presence is kept. */
101
+ const channelUsersPresent = new WeakMap();
102
+ /**
103
+ * The user's assigned roles, in order, and whether `signUp` created them. A database last migrated
104
+ * by an earlier SDK may lack `_channel_users`, or its `signed_up` column: nobody signed up there.
105
+ */
106
+ function storedRoles(sql, userId) {
107
+ return Effect.gen(function* () {
108
+ if (!channelUsersPresent.has(sql)) {
109
+ // @legacy ontology.pre-upgrade-database-tolerance
110
+ const [table] = yield* sql.unsafe(`SELECT to_regclass($1) IS NOT NULL AS "present"`, [
111
+ CHANNEL_USERS_TABLE,
112
+ ]);
113
+ if (table?.present !== true) {
114
+ const rows = yield* sql.unsafe(`SELECT "role" FROM "${USER_ROLES_TABLE}" WHERE "user_id" = $1::uuid ORDER BY "role"`, [userId]);
115
+ return {
116
+ roles: rows.map((row) => String(row.role)),
117
+ signedUp: false,
118
+ onboardingPending: false,
119
+ };
120
+ }
121
+ channelUsersPresent.set(sql, true);
122
+ }
123
+ const rows = yield* sql.unsafe(`SELECT "role", NULL AS "signed_up", NULL AS "pending" FROM "${USER_ROLES_TABLE}"
124
+ WHERE "user_id" = $1::uuid
125
+ UNION ALL
126
+ SELECT NULL, to_jsonb("c") ->> 'signed_up',
127
+ ("c"."on_new_user_completed_at" IS NULL AND "c"."blocked_at" IS NULL)::text
128
+ FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid
129
+ ORDER BY 1`, [userId]);
130
+ const lifecycle = rows.find((row) => row.role === null || row.role === undefined);
131
+ const signedUp = lifecycle?.signed_up === "true";
132
+ return {
133
+ roles: rows.flatMap((row) => (typeof row.role === "string" ? [row.role] : [])),
134
+ signedUp,
135
+ onboardingPending: signedUp && lifecycle?.pending === "true",
136
+ };
137
+ });
138
+ }
139
+ /**
140
+ * The principal of a user with their current roles. An active member holds `member` beside their
141
+ * assigned roles, unless `signUp` created them: they hold exactly what sign-up and later grants
142
+ * gave them. A service holds exactly the roles it was given.
143
+ */
100
144
  export function rolesOf(ontology, sql, user) {
145
+ return principalState(ontology, sql, user).pipe(Effect.map((state) => state.principal));
146
+ }
147
+ /** {@link rolesOf}, and whether a user sign-up created still waits for its `onSignUp` action. */
148
+ function principalState(ontology, sql, user) {
101
149
  return Effect.gen(function* () {
102
- const rows = yield* sql.unsafe(`SELECT "role" FROM "${USER_ROLES_TABLE}" WHERE "user_id" = $1::uuid ORDER BY "role"`, [user.id]);
150
+ const stored = yield* storedRoles(sql, user.id);
103
151
  // Ignore forged or historical stored assignments: reporter authority is never persisted.
104
- const assigned = rows
105
- .map((row) => String(row.role))
106
- .filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE);
107
- // Every active member holds `member`; a service holds exactly the roles it was given.
108
- const roles = user.kind === "member"
109
- ? [
110
- MEMBER_ROLE,
111
- ...assigned.filter((role) => role !== MEMBER_ROLE),
112
- ...(ontology.roles.some((role) => role.name === FEEDBACK_REPORTER_ROLE)
113
- ? [FEEDBACK_REPORTER_ROLE]
114
- : []),
115
- ]
116
- : assigned;
152
+ const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE);
153
+ const roles = user.kind === "member" && stored.signedUp
154
+ ? assigned.filter((role) => role !== MEMBER_ROLE)
155
+ : user.kind === "member"
156
+ ? [
157
+ MEMBER_ROLE,
158
+ ...assigned.filter((role) => role !== MEMBER_ROLE),
159
+ ...(ontology.roles.some((role) => role.name === FEEDBACK_REPORTER_ROLE)
160
+ ? [FEEDBACK_REPORTER_ROLE]
161
+ : []),
162
+ ]
163
+ : assigned;
117
164
  // A role the deployed ontology no longer declares grants nothing.
118
165
  return {
119
- id: user.id,
120
- kind: user.kind,
121
- roles,
122
- permissions: permissionsOf(ontology.roles, roles),
123
- ...principalScopes(ontology.roles, roles),
166
+ principal: {
167
+ id: user.id,
168
+ kind: user.kind,
169
+ roles,
170
+ permissions: permissionsOf(ontology.roles, roles),
171
+ ...principalScopes(ontology.roles, roles),
172
+ },
173
+ signUpPending: user.kind === "member" && stored.onboardingPending,
124
174
  };
125
175
  });
126
176
  }
127
177
  function activePrincipal(ontology, sql, user) {
178
+ return activePrincipalState(ontology, sql, user).pipe(Effect.map((state) => state.principal));
179
+ }
180
+ function activePrincipalState(ontology, sql, user) {
128
181
  return Effect.gen(function* () {
129
182
  if (!user.active || (user.kind === "member" && (yield* isMemberBlocked(sql, user.id)))) {
130
183
  return yield* new PrincipalRejected({
@@ -132,7 +185,7 @@ function activePrincipal(ontology, sql, user) {
132
185
  message: "The user is inactive.",
133
186
  });
134
187
  }
135
- return yield* rolesOf(ontology, sql, user);
188
+ return yield* principalState(ontology, sql, user);
136
189
  });
137
190
  }
138
191
  function userRow(record) {
@@ -303,7 +356,10 @@ function signIn(ontology, sql, claims) {
303
356
  yield* recordIdentity(String(invited.id), "invite");
304
357
  return userRow(linkedUser);
305
358
  }
306
- if (ontology.signIn.policy !== "open") {
359
+ // `signUp` with `email` creates a user holding its roles; `policy: "open"` one holding member.
360
+ const signUpRoles = signUpRolesOf(ontology.manifest, "email");
361
+ // @legacy ontology.legacy-channel-admission
362
+ if (signUpRoles === undefined && ontology.signIn.policy !== "open") {
307
363
  return yield* new PrincipalRejected({
308
364
  reason: "not_invited",
309
365
  message: "No member was invited with this identity or email.",
@@ -317,7 +373,12 @@ function signIn(ontology, sql, claims) {
317
373
  identity_subject: claims.identitySubject,
318
374
  ...signedIn,
319
375
  });
320
- yield* recordUserCreation(sql, String(created.id), "email");
376
+ yield* recordUserCreation(sql, String(created.id), "email", signUpRoles !== undefined);
377
+ if (signUpRoles !== undefined && signUpRoles.length > 0) {
378
+ yield* platformRuntime(ontology, sql, MEMBER_HISTORY_ACTIONS.grantRoles)
379
+ .members.grantRoles({ id: String(created.id), roles: signUpRoles })
380
+ .pipe(Effect.orDie);
381
+ }
321
382
  yield* recordIdentity(String(created.id), "sign_in");
322
383
  return userRow(created);
323
384
  }));
@@ -332,6 +393,13 @@ function signIn(ontology, sql, claims) {
332
393
  * deferred to a later request instead of delaying authentication. Inactive users are rejected.
333
394
  */
334
395
  export function resolvePrincipalByIdentity(ontology, claims) {
396
+ return resolveSignInState(ontology, claims).pipe(Effect.map((state) => state.principal));
397
+ }
398
+ /**
399
+ * {@link resolvePrincipalByIdentity}, and whether the user email sign-up created still waits for
400
+ * `onSignUp`. The caller runs it once nothing else holds a transaction; see `runNewUserHook`.
401
+ */
402
+ export function resolveSignInState(ontology, claims) {
335
403
  return Effect.gen(function* () {
336
404
  const sql = yield* SqlClient.SqlClient;
337
405
  const attempt = signIn(ontology, sql, claims);
@@ -340,7 +408,7 @@ export function resolvePrincipalByIdentity(ontology, claims) {
340
408
  reason: "identity_conflict",
341
409
  message: "The sign-in conflicts with another user.",
342
410
  }))));
343
- return yield* activePrincipal(ontology, sql, user);
411
+ return yield* activePrincipalState(ontology, sql, user);
344
412
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
345
413
  }
346
414
  /** Resolve the workspace's stable keyless pipeline service, without customer roles or sign-in. */
@@ -661,9 +729,14 @@ export function reconcileWorkflowUsers(ontology, input) {
661
729
  }
662
730
  /**
663
731
  * The principal of an API key, with the permissions its roles have in the ontology. Unknown and
664
- * revoked keys and inactive users are rejected.
732
+ * revoked keys and inactive users are rejected. A key with delegation resolves to its user too: the
733
+ * service authenticates its requests as the member they name, and refuses them otherwise.
665
734
  */
666
735
  export function resolvePrincipalByApiKey(ontology, key) {
736
+ return resolveApiKeyCredential(ontology, key).pipe(Effect.map(({ principal }) => principal));
737
+ }
738
+ /** An API key's principal and whether it acts with delegation; see {@link resolvePrincipalByApiKey}. */
739
+ export function resolveApiKeyCredential(ontology, key) {
667
740
  return Effect.gen(function* () {
668
741
  const sql = yield* SqlClient.SqlClient;
669
742
  const unknownKey = (diagnostic) => new PrincipalRejected({
@@ -676,7 +749,8 @@ export function resolvePrincipalByApiKey(ontology, key) {
676
749
  return yield* unknownKey("malformed_api_key");
677
750
  }
678
751
  const [row] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id", "u"."kind"::text AS "kind", "u"."active" AS "active", ` +
679
- `"k"."salt" AS "salt", "k"."hash" AS "hash", "k"."revoked_at" IS NOT NULL AS "revoked" ` +
752
+ `"k"."salt" AS "salt", "k"."hash" AS "hash", "k"."revoked_at" IS NOT NULL AS "revoked", ` +
753
+ `${API_KEY_DELEGATION} AS "delegation" ` +
680
754
  `FROM "${API_KEYS_TABLE}" AS "k" JOIN "${USER_TABLE}" AS "u" ON "u"."id" = "k"."user_id" ` +
681
755
  `WHERE "k"."key_id" = $1::text`, [parts.keyId]);
682
756
  // An unknown key id costs one KDF too, so that timing does not tell which key ids exist.
@@ -699,9 +773,17 @@ export function resolvePrincipalByApiKey(ontology, key) {
699
773
  message: "The API key was revoked.",
700
774
  });
701
775
  }
702
- return yield* activePrincipal(ontology, sql, decodeUser({ id: row.id, kind: row.kind, active: row.active }));
776
+ const principal = yield* activePrincipal(ontology, sql, decodeUser({ id: row.id, kind: row.kind, active: row.active }));
777
+ return { principal, delegation: row.delegation === true };
703
778
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
704
779
  }
780
+ /**
781
+ * Whether the API key `"k"` acts with delegation.
782
+ * @legacy ontology.pre-upgrade-database-tolerance
783
+ * Read through the row's JSON, so that a database an earlier SDK migrated, which has no such
784
+ * column until its next migration, reads every key as one without delegation.
785
+ */
786
+ const API_KEY_DELEGATION = `COALESCE((to_jsonb("k") ->> 'delegation')::boolean, false)`;
705
787
  /**
706
788
  * A member by user id, with the roles they hold now: whom an OAuth grant acts for. `undefined` for
707
789
  * an unknown user, a service and an inactive member.
@@ -720,7 +802,11 @@ export function resolveMemberById(ontology, userId) {
720
802
  return yield* rolesOf(ontology, sql, decodeUser(row));
721
803
  }).pipe(Effect.orDie);
722
804
  }
723
- /** Issues an API key for a user. */
805
+ /**
806
+ * Issues an API key for a user. With `delegation` the key acts only for the member each request
807
+ * names; the column is written only then, so that keys without it can still be issued on a
808
+ * database an earlier SDK migrated.
809
+ */
724
810
  export function createApiKey(input) {
725
811
  return Effect.gen(function* () {
726
812
  const sql = yield* SqlClient.SqlClient;
@@ -729,9 +815,13 @@ export function createApiKey(input) {
729
815
  const { keyId, secret } = parseApiKey(key);
730
816
  const salt = randomBytes(SALT_BYTES).toString("hex");
731
817
  const hash = yield* Effect.promise(() => hashApiKeySecret(secret, salt));
818
+ const delegation = input.delegation === true;
732
819
  yield* sql.unsafe(`INSERT INTO "${API_KEYS_TABLE}" ` +
733
- `("id", "user_id", "key_id", "salt", "hash", "label", "created_at") ` +
734
- "VALUES ($1::uuid, $2::uuid, $3::text, $4::text, $5::text, $6::text, now())", [id, input.userId, keyId, salt, hash, input.label]);
820
+ `("id", "user_id", "key_id", "salt", "hash", "label", "created_at"` +
821
+ (delegation ? `, "delegation"` : "") +
822
+ ") VALUES ($1::uuid, $2::uuid, $3::text, $4::text, $5::text, $6::text, now()" +
823
+ (delegation ? ", true" : "") +
824
+ ")", [id, input.userId, keyId, salt, hash, input.label]);
735
825
  return { id, key };
736
826
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
737
827
  }
@@ -777,7 +867,9 @@ export function setUserRoles(ontology, input) {
777
867
  }
778
868
  /**
779
869
  * Creates a service user with roles and a first API key, as the app or the CLI does for the
780
- * website's intake key.
870
+ * website's intake key. With `delegation` the service holds no role and its key acts only for the
871
+ * member each request names, as an external agent the workspace trusts does: roles and delegation
872
+ * never come together, so that such a key has no authority of its own.
781
873
  */
782
874
  export function createServiceUser(ontology, input) {
783
875
  return Effect.gen(function* () {
@@ -788,8 +880,15 @@ export function createServiceUser(ontology, input) {
788
880
  const user = yield* runtime
789
881
  .create({ entity: "user", values: { name: input.name, kind: "service" } })
790
882
  .pipe(Effect.orDie);
883
+ if (input.delegation === true && input.roles.length > 0) {
884
+ return yield* Effect.die(new Error("A key with delegation acts with its member's roles and holds none of its own."));
885
+ }
791
886
  yield* setUserRoles(ontology, { userId: user.id, roles: input.roles });
792
- const apiKey = yield* createApiKey({ userId: user.id, label: input.keyLabel });
887
+ const apiKey = yield* createApiKey({
888
+ userId: user.id,
889
+ label: input.keyLabel,
890
+ ...(input.delegation === true ? { delegation: true } : {}),
891
+ });
793
892
  return { user, apiKey };
794
893
  }));
795
894
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
@@ -872,6 +971,7 @@ const ApiKeyRow = Schema.Struct({
872
971
  user_name: Schema.String,
873
972
  user_active: Schema.Boolean,
874
973
  roles: Schema.Array(Schema.String),
974
+ delegation: Schema.Boolean,
875
975
  });
876
976
  const decodeApiKeyRow = Schema.decodeUnknownSync(ApiKeyRow);
877
977
  function apiKeySummary(raw) {
@@ -884,6 +984,7 @@ function apiKeySummary(raw) {
884
984
  revokedAt: row.revoked_at ?? undefined,
885
985
  user: { id: row.user_id, name: row.user_name, active: row.user_active },
886
986
  roles: row.roles.filter((assigned) => toSnakeCase(assigned) !== FEEDBACK_REPORTER_ROLE),
987
+ delegation: row.delegation,
887
988
  };
888
989
  }
889
990
  /** The roles assigned to the user `"u"`, sorted, as one text array. */
@@ -894,6 +995,7 @@ const API_KEY_COLUMNS = `"k"."id"::text AS "id", "k"."key_id" AS "key_id", "k"."
894
995
  `to_char("k"."created_at" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "created_at", ` +
895
996
  `to_char("k"."revoked_at" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "revoked_at", ` +
896
997
  `"u"."id"::text AS "user_id", "u"."name" AS "user_name", "u"."active" AS "user_active", ` +
998
+ `${API_KEY_DELEGATION} AS "delegation", ` +
897
999
  ROLES_OF_USER;
898
1000
  const API_KEY_FROM = `FROM "${API_KEYS_TABLE}" AS "k" JOIN "${USER_TABLE}" AS "u" ON "u"."id" = "k"."user_id"`;
899
1001
  /** Every API key, oldest first, revoked ones included. */
@@ -1060,16 +1162,18 @@ export function checkSignIn(ontology, email) {
1060
1162
  : `("u"."identity_provider" = $2 AND "u"."identity_subject" IS NOT NULL)`;
1061
1163
  const [row] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id", "u"."active" AS "active", ${neonAuth} AS "neon_auth" ` +
1062
1164
  `FROM "${USER_TABLE}" AS "u" WHERE "u"."kind" = 'member' AND "u"."email" = $1 LIMIT 1`, [address, NEON_AUTH_PROVIDER]);
1165
+ // Anyone may sign in where email is open to sign-up, so the answer reveals nothing.
1166
+ const open = signUpRolesOf(ontology.manifest, "email") !== undefined ||
1167
+ // @legacy ontology.legacy-channel-admission
1168
+ ontology.signIn.policy === "open";
1063
1169
  if (row === undefined) {
1064
- return ontology.signIn.policy === "open"
1065
- ? { allowed: true, method: "link" }
1066
- : { allowed: false };
1170
+ return open ? { allowed: true, method: "link" } : { allowed: false };
1067
1171
  }
1068
1172
  const member = decodeSignInRow(row);
1069
1173
  if (yield* isMemberBlocked(sql, member.id)) {
1070
1174
  return { allowed: false };
1071
1175
  }
1072
- if (ontology.signIn.policy === "open") {
1176
+ if (open) {
1073
1177
  return { allowed: true, method: "link" };
1074
1178
  }
1075
1179
  if (!member.active) {