@fabrika/iam 0.9.0-dev.36 → 0.9.0-dev.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ -- A grant holds a set of values of one dimension, one row per value (ADR-0085). SQLite/D1 dialect;
2
+ -- `../migrations-postgres/0036_grant_scope_sets.sql` states the same outcome.
3
+ --
4
+ -- The rows of a grant with more than one value share `scope_set`, the grant's id. NULL is a grant of one value, which
5
+ -- is every grant written before this file, so each of them stays the grant it was and resolves as before.
6
+ ALTER TABLE grants ADD COLUMN scope_set TEXT;
7
+ CREATE INDEX idx_grants_scope_set ON grants(scope_set);
8
+
9
+ -- The values a dimension lists for the console, a JSON array of { value, label? }; NULL lists none.
10
+ ALTER TABLE app_scopes ADD COLUMN value_list TEXT;
11
+
12
+ -- Every value a waiting grant change asks for (ADR-0083), a JSON array, when it asks for more than one; `scope_value`
13
+ -- keeps the first. NULL is a request of one value or none, which is every request written before this file.
14
+ ALTER TABLE grant_requests ADD COLUMN scope_values TEXT;
@@ -0,0 +1,14 @@
1
+ -- A grant holds a set of values of one dimension, one row per value (ADR-0085). Postgres dialect;
2
+ -- `../migrations/0036_grant_scope_sets.sql` states the same outcome.
3
+ --
4
+ -- The rows of a grant with more than one value share `scope_set`, the grant's id. NULL is a grant of one value, which
5
+ -- is every grant written before this file, so each of them stays the grant it was and resolves as before.
6
+ ALTER TABLE grants ADD COLUMN scope_set TEXT;
7
+ CREATE INDEX idx_grants_scope_set ON grants(scope_set);
8
+
9
+ -- The values a dimension lists for the console, a JSON array of { value, label? }; NULL lists none.
10
+ ALTER TABLE app_scopes ADD COLUMN value_list TEXT;
11
+
12
+ -- Every value a waiting grant change asks for (ADR-0083), a JSON array, when it asks for more than one; `scope_value`
13
+ -- keeps the first. NULL is a request of one value or none, which is every request written before this file.
14
+ ALTER TABLE grant_requests ADD COLUMN scope_values TEXT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/iam",
3
- "version": "0.9.0-dev.36",
3
+ "version": "0.9.0-dev.37",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -56,16 +56,16 @@
56
56
  "prune:auth-log": "bun src/node/prune.ts"
57
57
  },
58
58
  "dependencies": {
59
- "@fabrika/app": "0.9.0-dev.36",
60
- "@fabrika/auth": "0.9.0-dev.36",
61
- "@fabrika/auth-core": "0.9.0-dev.36",
62
- "@fabrika/control-contract": "0.9.0-dev.36",
63
- "@fabrika/email": "0.9.0-dev.36",
64
- "@fabrika/iam-contract": "0.9.0-dev.36",
65
- "@fabrika/platform": "0.9.0-dev.36",
66
- "@fabrika/platform-node": "0.9.0-dev.36",
67
- "@fabrika/provider-cloudflare": "0.9.0-dev.36",
68
- "@fabrika/proxy-core": "0.9.0-dev.36",
59
+ "@fabrika/app": "0.9.0-dev.37",
60
+ "@fabrika/auth": "0.9.0-dev.37",
61
+ "@fabrika/auth-core": "0.9.0-dev.37",
62
+ "@fabrika/control-contract": "0.9.0-dev.37",
63
+ "@fabrika/email": "0.9.0-dev.37",
64
+ "@fabrika/iam-contract": "0.9.0-dev.37",
65
+ "@fabrika/platform": "0.9.0-dev.37",
66
+ "@fabrika/platform-node": "0.9.0-dev.37",
67
+ "@fabrika/provider-cloudflare": "0.9.0-dev.37",
68
+ "@fabrika/proxy-core": "0.9.0-dev.37",
69
69
  "jose": "^5.9.0",
70
70
  "uqr": "^0.1.3",
71
71
  "zod": "^3.25.76"
@@ -119,7 +119,7 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
119
119
  }
120
120
  const scope = parseScope(input)
121
121
  if (!scope.ok) {
122
- return fail(400, 'scopeType and scopeValue must be both set or both omitted')
122
+ return fail(400, scope.message)
123
123
  }
124
124
  const contractProblem = await contractGrantProblem(c.services.repositories.appSchema, app, { ...roleOrInline, scopeType: scope.scopeType }, false)
125
125
  if (contractProblem !== null) {
@@ -139,13 +139,13 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
139
139
  const { principals, grants, credentials, audit } = c.services.repositories
140
140
  await audit.commit([
141
141
  principals.createServiceStatement(principalId, label),
142
- grants.grantStatement(grantId, {
142
+ ...grants.grantSetStatements(grantId, {
143
143
  principalId,
144
144
  app,
145
145
  roleKey: roleOrInline.roleKey,
146
146
  permissions: roleOrInline.permissions,
147
147
  scopeType: scope.scopeType,
148
- scopeValue: scope.scopeValue,
148
+ scopeValues: scope.scopeValues,
149
149
  grantedBy: c.admin.id,
150
150
  expiresAt,
151
151
  }),
@@ -176,7 +176,8 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
176
176
  roleKey: roleOrInline.roleKey,
177
177
  permissions: roleOrInline.permissions,
178
178
  scopeType: scope.scopeType,
179
- scopeValue: scope.scopeValue,
179
+ scopeValue: scope.scopeValues?.[0] ?? null,
180
+ ...(scope.scopeValues !== null && scope.scopeValues.length > 1 ? { scopeValues: scope.scopeValues } : {}),
180
181
  app,
181
182
  },
182
183
  })),
@@ -268,9 +269,10 @@ const provisionApiKeyRequestSchema = z.object({
268
269
  permissions: z.array(z.string()).optional().catch(undefined),
269
270
  scopeType: z.string().nullable().optional().catch(undefined),
270
271
  scopeValue: z.string().nullable().optional().catch(undefined),
272
+ scopeValues: z.array(z.string()).optional().catch(undefined),
271
273
  app: z.string().nullable().optional().catch(undefined),
272
274
  expiresAt: z.number().finite().optional().catch(undefined),
273
- }).transform(({ label, type, roleKey, permissions, scopeType, scopeValue, app, expiresAt }) => {
275
+ }).transform(({ label, type, roleKey, permissions, scopeType, scopeValue, scopeValues, app, expiresAt }) => {
274
276
  return {
275
277
  label,
276
278
  type,
@@ -278,6 +280,7 @@ const provisionApiKeyRequestSchema = z.object({
278
280
  ...(permissions !== undefined ? { permissions } : {}),
279
281
  ...(scopeType !== undefined ? { scopeType } : {}),
280
282
  ...(scopeValue !== undefined ? { scopeValue } : {}),
283
+ ...(scopeValues !== undefined ? { scopeValues } : {}),
281
284
  ...(app !== undefined ? { app } : {}),
282
285
  ...(expiresAt !== undefined ? { expiresAt } : {}),
283
286
  }
@@ -188,7 +188,7 @@ export async function grantAppRole(ctx: IamAppContext, input: GrantAppRoleReques
188
188
  roleKey: role.role_key,
189
189
  permissions: null,
190
190
  scopeType: null,
191
- scopeValue: null,
191
+ scopeValues: null,
192
192
  grantExpiresAt: expiresAt,
193
193
  requestedBy: admin.principal.id,
194
194
  }, (requestId, metadata) =>
@@ -236,7 +236,7 @@ export async function revokeAppRole(ctx: IamAppContext, input: RevokeAppRoleRequ
236
236
  roleKey: role.role_key,
237
237
  permissions: null,
238
238
  scopeType: null,
239
- scopeValue: null,
239
+ scopeValues: null,
240
240
  grantExpiresAt: held.expires_at,
241
241
  requestedBy: admin.principal.id,
242
242
  }, (requestId, metadata) =>
@@ -1,5 +1,5 @@
1
1
  import { appSchemaSchema } from '@fabrika/auth'
2
- import { type AppDelegationDef, type AppLinkMountDef, LOCALES, type RoleDef } from '@fabrika/auth-core'
2
+ import { type AppDelegationDef, type AppLinkMountDef, type DimensionValue, LOCALES, type RoleDef } from '@fabrika/auth-core'
3
3
 
4
4
  import {
5
5
  type AppDto,
@@ -14,7 +14,7 @@ import type { z } from 'zod'
14
14
  import { parsePresentation } from '../app-presentation'
15
15
  import { normalizeOrigin } from '../handoff'
16
16
  import { BUILTIN_ROLES } from '../roles'
17
- import { parseStoredPermissions } from '../stored-permissions'
17
+ import { parseStoredPermissions, parseStoredValueList } from '../stored-permissions'
18
18
  import { type AdminContext, adminEvent, fail } from './context'
19
19
  import { dbRoleToDef, knownApps } from './grant-support'
20
20
  import { error, json, readJson } from './http'
@@ -176,6 +176,7 @@ export async function putAppSchema(c: AdminContext, app: string): Promise<Respon
176
176
  members: s.members ?? null,
177
177
  directory: s.directory ?? null,
178
178
  lookups: s.lookups ?? null,
179
+ values: s.values ?? null,
179
180
  })),
180
181
  actions: schema.actions.map((a) => ({ action: a.action, description: a.description ?? null })),
181
182
  roles: Object.entries(schema.roles).map(([roleKey, def]) => ({
@@ -252,6 +253,7 @@ async function readAppSchemaDto(c: AdminContext, app: string): Promise<AppSchema
252
253
  ...(r.members_manage !== null && r.members_list !== null ? { members: { manage: r.members_manage, list: r.members_list } } : {}),
253
254
  ...(r.members_directory === 'labels' ? { directory: 'labels' } : {}),
254
255
  ...(r.members_lookup === null ? {} : { lookups: parseStoredPermissions(r.members_lookup) }),
256
+ ...valueListOf(r.value_list),
255
257
  })),
256
258
  actions: actionRows.map((r) => ({ action: r.action, ...(r.description !== null ? { description: r.description } : {}) })),
257
259
  roles,
@@ -306,3 +308,9 @@ export async function getAppSchemaUseCase(c: AdminContext, input: AppInput): Pro
306
308
  }
307
309
  return readAppSchemaDto(c, app)
308
310
  }
311
+
312
+ /** A scope's listed values as the schema answers them: present only when the stored list parses. */
313
+ function valueListOf(stored: string | null): { values?: DimensionValue[] } {
314
+ const values = parseStoredValueList(stored)
315
+ return values === null ? {} : { values }
316
+ }
@@ -15,12 +15,13 @@ import {
15
15
  import { uuidv7 } from '@fabrika/platform'
16
16
  import { PROVISIONING_ADMIN_ID } from '../auth'
17
17
  import { contractGrantProblem, externalGrantProblem } from '../contract-rules'
18
- import { type AuditEventInput, auditLabelOf, type CreateGrantRequestInput, type GrantRequestRow, type GrantRow } from '../db'
18
+ import { type AuditEventInput, auditLabelOf, type CreateGrantRequestInput, ExternalGrantError, type GrantRequestRow, type GrantSetRead } from '../db'
19
+ import { requestScopeValues } from '../repositories/grants'
19
20
  import { unixNow } from '../repositories/sql'
20
21
  import type { Services } from '../services'
21
22
  import { parseStoredPermissions } from '../stored-permissions'
22
23
  import { type AdminContext, adminEvent, fail } from './context'
23
- import { appField, parseRoleOrInline } from './grant-support'
24
+ import { appField, grantIdOf, parseRoleOrInline } from './grant-support'
24
25
  import type { ResolvedAdmin } from './router'
25
26
  import { managesApp, requireGrantablePrincipal } from './user-admin'
26
27
 
@@ -50,7 +51,8 @@ export async function requestGrantChange(
50
51
  roleKey: change.roleKey,
51
52
  permissions: change.permissions,
52
53
  scopeType: change.scopeType,
53
- scopeValue: change.scopeValue,
54
+ scopeValue: change.scopeValues?.[0] ?? null,
55
+ ...(change.scopeValues !== null && change.scopeValues.length > 1 ? { scopeValues: change.scopeValues } : {}),
54
56
  }),
55
57
  )
56
58
  return toGrantRequestDto(services, row, now)
@@ -97,22 +99,32 @@ export async function decideGrantRequestUseCase(c: AdminContext, person: boolean
97
99
  const current = await approvable(c, request)
98
100
  const decision = { id: uuidv7(), by: c.admin.id, at: now }
99
101
  const action = request.kind === 'create' ? 'iam.grant.create' : request.kind === 'update' ? 'iam.grant.update' : 'iam.grant.revoke'
100
- const applied = await c.services.repositories.grants.applyRequest(request, current, decision, (grantId) =>
101
- adminEvent(c, {
102
- action,
103
- resourceType: 'grant',
104
- resourceId: grantId,
105
- metadata: {
106
- principalId: request.principal_id,
107
- app: request.app,
108
- roleKey: request.role_key,
109
- permissions: request.permissions === null ? null : parseStoredPermissions(request.permissions),
110
- scopeType: request.scope_type,
111
- scopeValue: request.scope_value,
112
- grantRequestId: request.id,
113
- requestedBy: request.requested_by,
114
- },
115
- }))
102
+ const scopeValues = requestScopeValues(request)
103
+ let applied: Awaited<ReturnType<typeof c.services.repositories.grants.applyRequest>>
104
+ try {
105
+ applied = await c.services.repositories.grants.applyRequest(request, current, decision, (grantId) =>
106
+ adminEvent(c, {
107
+ action,
108
+ resourceType: 'grant',
109
+ resourceId: grantId,
110
+ metadata: {
111
+ principalId: request.principal_id,
112
+ app: request.app,
113
+ roleKey: request.role_key,
114
+ permissions: request.permissions === null ? null : parseStoredPermissions(request.permissions),
115
+ scopeType: request.scope_type,
116
+ scopeValue: scopeValues?.[0] ?? null,
117
+ ...(scopeValues !== null && scopeValues.length > 1 ? { scopeValues } : {}),
118
+ grantRequestId: request.id,
119
+ requestedBy: request.requested_by,
120
+ },
121
+ }))
122
+ } catch (cause) {
123
+ // Both roll the whole batch back, the claim included: the request stays open for a later decision or a rejection.
124
+ if (cause instanceof ExternalGrantError) return fail(409, `${cause.message}; reject the request`)
125
+ if (await heldElsewhere(c, request)) return fail(409, 'the principal already holds this grant; reject the request')
126
+ throw cause
127
+ }
116
128
  if (!applied.claimed) return fail(409, 'the grant request is no longer open')
117
129
  if (applied.changed === null) {
118
130
  return fail(409, 'the change no longer applies: the access changed since the checks; the request is closed as failed')
@@ -164,14 +176,15 @@ export async function withdrawOwnGrantRequestUseCase(c: GrantRequester, input: D
164
176
  * The checks the original change ran, again, with the approver as the administrator: the approver must be able to make
165
177
  * the change now. Answers the grant an `update` or a `revoke` acts on.
166
178
  */
167
- async function approvable(c: AdminContext, request: GrantRequestRow): Promise<GrantRow | null> {
179
+ async function approvable(c: AdminContext, request: GrantRequestRow): Promise<GrantSetRead | null> {
168
180
  const { grants, principals, appSchema } = c.services.repositories
169
181
  const principal = await principals.getPrincipalById(request.principal_id)
170
182
  if (principal === null) return fail(409, 'the principal no longer exists; reject the request')
171
183
  if (await grants.isWorkloadPrincipal(principal.id)) return fail(409, 'a job, a webhook or a connector holds no grant')
172
184
  requireGrantablePrincipal(c, principal)
173
- const current = request.grant_id === null ? null : await grants.getGrantById(request.grant_id)
174
- if (request.kind !== 'create' && (current === null || current.app !== request.app || current.principal_id !== principal.id)) {
185
+ const current = request.grant_id === null ? null : await grants.getGrantSet(request.grant_id)
186
+ const [held] = current?.rows ?? []
187
+ if (request.kind !== 'create' && (held === undefined || held.app !== request.app || held.principal_id !== principal.id)) {
175
188
  return fail(409, 'the grant is gone; reject the request')
176
189
  }
177
190
  if (request.kind === 'revoke') return current
@@ -190,17 +203,26 @@ async function approvable(c: AdminContext, request: GrantRequestRow): Promise<Gr
190
203
  const problem = await contractGrantProblem(appSchema, request.app, authorization, principal.type === 'user')
191
204
  ?? await externalGrantProblem(appSchema, principal, request.app, authorization)
192
205
  if (problem !== null) return fail(409, problem)
193
- if (request.role_key !== null) {
194
- const held = (await grants.listGrants(principal.id)).some((grant) =>
195
- grant.id !== request.grant_id && grant.app === request.app && grant.role_key === request.role_key
196
- && grant.scope_type === request.scope_type && grant.scope_value === request.scope_value
197
- && (grant.expires_at === null || grant.expires_at > unixNow())
198
- )
199
- if (held) return fail(409, 'the principal already holds this grant; reject the request')
200
- }
206
+ if (await heldElsewhere(c, request)) return fail(409, 'the principal already holds this grant; reject the request')
201
207
  return current
202
208
  }
203
209
 
210
+ /**
211
+ * Whether another grant of the principal already holds the requested role in one of the requested values. A scoped one
212
+ * counts expired too: the unique index refuses the value either way; only an expired app-wide grant is renewed in place.
213
+ */
214
+ async function heldElsewhere(c: AdminContext, request: GrantRequestRow): Promise<boolean> {
215
+ if (request.role_key === null) return false
216
+ const values = requestScopeValues(request)
217
+ return (await c.services.repositories.grants.listGrants(request.principal_id)).some((grant) =>
218
+ grantIdOf(grant) !== request.grant_id && grant.app === request.app && grant.role_key === request.role_key
219
+ && grant.scope_type === request.scope_type
220
+ && (values === null
221
+ ? grant.scope_value === null && (grant.expires_at === null || grant.expires_at > unixNow())
222
+ : grant.scope_value !== null && values.includes(grant.scope_value))
223
+ )
224
+ }
225
+
204
226
  /**
205
227
  * Make grant changes at `app` wait, or apply at once again (ADR-0083 §4). Only Control sets it, with the provisioning
206
228
  * key, when an environment chooses or drops the `grants` category: an installation administrator who could switch it
@@ -241,6 +263,7 @@ async function toGrantRequestDto(services: Services, row: GrantRequestRow, now:
241
263
  permissions: row.permissions === null ? null : parseStoredPermissions(row.permissions),
242
264
  scopeType: row.scope_type,
243
265
  scopeValue: row.scope_value,
266
+ scopeValues: requestScopeValues(row),
244
267
  grantExpiresAt: row.grant_expires_at,
245
268
  requestedBy: row.requested_by,
246
269
  requestedByLabel: (await principals.getPrincipalById(row.requested_by))?.label ?? null,
@@ -1,5 +1,5 @@
1
1
  import { isActionAllowed, isReservedScopeType, parseJsonStringArray, type RoleDef } from '@fabrika/auth-core'
2
- import { type CreateGrantRequest, type GrantDto } from '@fabrika/iam-contract'
2
+ import { type CreateGrantRequest, type GrantDto, MAX_GRANT_SCOPE_VALUES } from '@fabrika/iam-contract'
3
3
  import { type GrantRow, type RoleRow } from '../db'
4
4
  import { BUILTIN_ROLES, isKnownRole } from '../roles'
5
5
  import { type Services } from '../services'
@@ -44,28 +44,55 @@ export class RoleKnownCache {
44
44
  }
45
45
  }
46
46
 
47
- export async function toGrantDto(row: GrantRow, roleCache: RoleKnownCache): Promise<GrantDto> {
47
+ /** The id of the grant a row belongs to: its set's, or its own for a grant of one value (ADR-0085). */
48
+ export function grantIdOf(row: Pick<GrantRow, 'id' | 'scope_set'>): string {
49
+ return row.scope_set ?? row.id
50
+ }
51
+
52
+ /** Rows grouped into grants by `grantIdOf`, in the order each grant's first row appears. */
53
+ export function grantSets(rows: readonly GrantRow[]): GrantRow[][] {
54
+ const sets = new Map<string, GrantRow[]>()
55
+ for (const row of rows) {
56
+ const id = grantIdOf(row)
57
+ const set = sets.get(id)
58
+ if (set === undefined) sets.set(id, [row])
59
+ else set.push(row)
60
+ }
61
+ return [...sets.values()]
62
+ }
63
+
64
+ /**
65
+ * One grant's DTO from the rows of its set. A row an assignment renewed may expire later than the rest, so the latest
66
+ * expiry counts (none wins): the grant reads as expired only once none of its values grants anything.
67
+ */
68
+ export async function toGrantDto(rows: readonly [GrantRow, ...GrantRow[]], roleCache: RoleKnownCache): Promise<GrantDto> {
69
+ const [row] = rows
48
70
  const dangling = row.role_key !== null && !(await roleCache.isKnown(row.role_key, row.app))
71
+ const scopeValues = row.scope_type === null
72
+ ? null
73
+ : rows.flatMap((each) => each.scope_value === null ? [] : [each.scope_value]).sort((a, b) => a < b ? -1 : a > b ? 1 : 0)
49
74
  return {
50
- id: row.id,
75
+ id: grantIdOf(row),
51
76
  principalId: row.principal_id,
52
77
  roleKey: row.role_key,
53
78
  permissions: row.permissions === null ? null : rolePermissions(row.permissions),
54
79
  scopeType: row.scope_type,
55
- scopeValue: row.scope_value,
80
+ scopeValue: scopeValues?.[0] ?? null,
81
+ scopeValues,
56
82
  app: row.app,
57
83
  grantedBy: row.granted_by,
58
- expiresAt: row.expires_at,
59
- createdAt: row.created_at,
84
+ expiresAt: rows.some((each) => each.expires_at === null) ? null : Math.max(...rows.flatMap((each) => each.expires_at ?? [])),
85
+ createdAt: Math.min(...rows.map((each) => each.created_at)),
60
86
  dangling,
61
87
  }
62
88
  }
63
89
 
64
- /** Map a list of grant rows to DTOs sharing one role-known cache (one query per app). */
90
+ /** Map grant rows to one DTO per grant, sharing one role-known cache (one query per app). */
65
91
  export async function toGrantDtos(rows: GrantRow[], services: Services, cache: RoleKnownCache = new RoleKnownCache(services)): Promise<GrantDto[]> {
66
92
  const out: GrantDto[] = []
67
- for (const row of rows) {
68
- out.push(await toGrantDto(row, cache))
93
+ for (const set of grantSets(rows)) {
94
+ const [first, ...rest] = set
95
+ if (first !== undefined) out.push(await toGrantDto([first, ...rest], cache))
69
96
  }
70
97
  return out
71
98
  }
@@ -119,22 +146,33 @@ async function loadAppRoleMap(c: AdminContext, app: string | null): Promise<Reco
119
146
  }
120
147
 
121
148
  /**
122
- * Validate the scope coordinate on a grant/key request: `scopeType`/`scopeValue` are
123
- * both-or-neither (both null = global). A half-set pair is a 400.
149
+ * Validate the scope coordinate on a grant/key request: `scopeType` with `scopeValue` or `scopeValues` (ADR-0085), or
150
+ * none of them (global). The values come back sorted, so a set reads the same whatever order the request listed.
124
151
  */
125
152
  export function parseScope(
126
- body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue'>,
127
- ): { ok: true; scopeType: string | null; scopeValue: string | null } | { ok: false } {
153
+ body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue' | 'scopeValues'>,
154
+ ): { ok: true; scopeType: string | null; scopeValues: string[] | null } | { ok: false; message: string } {
128
155
  const scopeType = body.scopeType ?? null
129
- const scopeValue = body.scopeValue ?? null
130
- if ((scopeType === null) !== (scopeValue === null)) {
131
- return { ok: false }
156
+ if (body.scopeValues !== undefined && body.scopeValue != null) {
157
+ return { ok: false, message: 'give scopeValue or scopeValues, not both' }
158
+ }
159
+ const scopeValues = body.scopeValues ?? (body.scopeValue == null ? null : [body.scopeValue])
160
+ if ((scopeType === null) !== (scopeValues === null)) {
161
+ return { ok: false, message: 'scopeType and scopeValue must be both set or both omitted' }
132
162
  }
133
163
  // A `~` scope type is IAM's derived pseudo-scope (`~rel`); a stored grant never names one.
134
164
  if (scopeType !== null && isReservedScopeType(scopeType)) {
135
- return { ok: false }
165
+ return { ok: false, message: 'scopeType and scopeValue must be both set or both omitted' }
166
+ }
167
+ if (scopeValues === null) return { ok: true, scopeType, scopeValues }
168
+ if (scopeValues.length === 0 || scopeValues.length > MAX_GRANT_SCOPE_VALUES) {
169
+ return { ok: false, message: `scopeValues must list 1 to ${MAX_GRANT_SCOPE_VALUES} values` }
136
170
  }
137
- return { ok: true, scopeType, scopeValue }
171
+ if (body.scopeValues !== undefined && scopeValues.includes('')) return { ok: false, message: 'a scope value must not be empty' }
172
+ const sorted = [...scopeValues].sort((a, b) => a < b ? -1 : a > b ? 1 : 0)
173
+ const repeated = sorted.find((value, index) => index > 0 && sorted[index - 1] === value)
174
+ if (repeated !== undefined) return { ok: false, message: `scopeValues lists '${repeated}' twice` }
175
+ return { ok: true, scopeType, scopeValues: sorted }
138
176
  }
139
177
 
140
178
  /**