@filelayer/core 0.3.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 (69) hide show
  1. package/CHANGELOG.md +338 -0
  2. package/LICENSE +202 -0
  3. package/MIGRATIONS.md +328 -0
  4. package/NOTICE +37 -0
  5. package/README.md +343 -0
  6. package/SEMANTICS.md +729 -0
  7. package/dist/authz.d.ts +524 -0
  8. package/dist/authz.d.ts.map +1 -0
  9. package/dist/authz.js +889 -0
  10. package/dist/authz.js.map +1 -0
  11. package/dist/db.d.ts +145 -0
  12. package/dist/db.d.ts.map +1 -0
  13. package/dist/db.js +217 -0
  14. package/dist/db.js.map +1 -0
  15. package/dist/delivery.d.ts +293 -0
  16. package/dist/delivery.d.ts.map +1 -0
  17. package/dist/delivery.js +519 -0
  18. package/dist/delivery.js.map +1 -0
  19. package/dist/errors.d.ts +16 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +21 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/filelayer.d.ts +542 -0
  24. package/dist/filelayer.d.ts.map +1 -0
  25. package/dist/filelayer.js +1360 -0
  26. package/dist/filelayer.js.map +1 -0
  27. package/dist/index.d.ts +8 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +8 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/simple.d.ts +297 -0
  32. package/dist/simple.d.ts.map +1 -0
  33. package/dist/simple.js +492 -0
  34. package/dist/simple.js.map +1 -0
  35. package/dist/storage.d.ts +269 -0
  36. package/dist/storage.d.ts.map +1 -0
  37. package/dist/storage.js +700 -0
  38. package/dist/storage.js.map +1 -0
  39. package/dist/store.d.ts +432 -0
  40. package/dist/store.d.ts.map +1 -0
  41. package/dist/store.js +862 -0
  42. package/dist/store.js.map +1 -0
  43. package/package.json +77 -0
  44. package/schema.sql +1190 -0
  45. package/src/authz.ts +1398 -0
  46. package/src/db.ts +271 -0
  47. package/src/delivery.ts +737 -0
  48. package/src/errors.ts +24 -0
  49. package/src/filelayer.ts +1836 -0
  50. package/src/index.ts +7 -0
  51. package/src/simple.ts +666 -0
  52. package/src/storage.ts +917 -0
  53. package/src/store.ts +1072 -0
  54. package/test/delivery.test.ts +0 -0
  55. package/test/group-subjects.test.ts +1072 -0
  56. package/test/helpers.ts +65 -0
  57. package/test/listing.test.ts +689 -0
  58. package/test/local-s3.d.mts +33 -0
  59. package/test/local-s3.mjs +400 -0
  60. package/test/persistence.test.ts +953 -0
  61. package/test/regression.test.ts +619 -0
  62. package/test/s3-live.test.ts +322 -0
  63. package/test/security.test.ts +1652 -0
  64. package/test/semantics.test.ts +888 -0
  65. package/test/storage.test.ts +437 -0
  66. package/test/tiers.test.ts +432 -0
  67. package/test/vault-example.test.ts +302 -0
  68. package/tsconfig.build.json +29 -0
  69. package/tsconfig.json +19 -0
package/dist/authz.js ADDED
@@ -0,0 +1,889 @@
1
+ /**
2
+ * FILELAYER AUTHORIZATION ENGINE
3
+ *
4
+ * Every access question in the system is answered here. There is deliberately
5
+ * no second path. Reads, writes, deletes, shares, signed-URL redemptions,
6
+ * membership changes, file creation and audit access all resolve through this
7
+ * module, against one decision core (`allow` / `deny`).
8
+ *
9
+ * The engine has exactly two resource scopes:
10
+ *
11
+ * authorize() (actor, file, capability) -- file-scoped
12
+ * authorizeOrg() (actor, org, org capability) -- org-scoped
13
+ *
14
+ * The org scope exists because some privileges are not about a file: creating
15
+ * one, reading the audit log, and changing who is in the organization. Those
16
+ * used to be hand-rolled checks in the API layer or entirely absent.
17
+ * Membership is a privilege change like any other, so it goes through
18
+ * the same path, with the same deny reasons and the same audit guarantee.
19
+ *
20
+ * WHY ONE ENGINE MATTERS MORE THAN IT LOOKS:
21
+ * The design goal is to minimise the "number of security-sensitive decisions a
22
+ * developer must make". In a hand-rolled integration built directly on Supabase,
23
+ * Convex or Vercel, that number scales with the number of *places* the
24
+ * developer touches files:
25
+ * every route, every RLS policy, every presign call is an independent chance
26
+ * to leak. Here the developer makes none of them, because there is exactly one
27
+ * place a decision can be made and it is not in the application.
28
+ *
29
+ * INVARIANTS (mirrored from schema.sql, enforced here in code):
30
+ * P1 deny by default - DENY unless a rule fires, at the file
31
+ * boundary as well as the tenant boundary
32
+ * P2 no ambient authority - storage keys/URLs/ids are never inputs
33
+ * P4 URL <= permission - redemption re-validates the grant AND its
34
+ * whole ancestor chain, always
35
+ * P5 audit every decision - every return path emits exactly one event,
36
+ * including decisions with no tenant to charge
37
+ *
38
+ * EVALUATION ORDER IS A SECURITY PROPERTY:
39
+ * 1. Does the file exist? -> no: deny, audit to the system chain
40
+ * 2. Does the caller have STANDING? -> no: deny, and say nothing more
41
+ * 3. Does their standing carry the requested capability?
42
+ * 4. Only then: lifecycle gates (deleted / expired / not ready / retained)
43
+ *
44
+ * Steps 1-3 are indistinguishable to the caller: everything is 404. The
45
+ * lifecycle statuses that are NOT 404 (410 Gone, 409 retention hold) are only
46
+ * ever reachable by someone who has already proven they may perform the
47
+ * operation, so they cannot be used to probe for the existence of a file.
48
+ * Previously these gates ran first and the API layer patched over the resulting
49
+ * oracle; that patch is gone.
50
+ */
51
+ export const ALL_CAPABILITIES = ['read', 'write', 'delete', 'share'];
52
+ const ALL_ROLES = ['viewer', 'member', 'admin', 'owner'];
53
+ const ALL_VISIBILITIES = ['private', 'org'];
54
+ const ALL_STATES = ['pending', 'ready', 'deleted'];
55
+ /** Ordered so comparisons are possible. Higher index = strictly more power. */
56
+ const ROLE_RANK = {
57
+ viewer: 0,
58
+ member: 1,
59
+ admin: 2,
60
+ owner: 3,
61
+ };
62
+ /**
63
+ * The subject types an issuer whose authority is GRANT-DERIVED may mint (I6).
64
+ *
65
+ * `actor` names one person and `link` is a bearer credential for one file;
66
+ * neither widens the population the issuer could already reach. `org`, `role`
67
+ * and `anonymous` all do, so a delegate may not create them at any depth.
68
+ *
69
+ * Exported so the rule is nameable in one place and testable directly, and so
70
+ * that adding a sixth subject type forces a decision about it here rather than
71
+ * silently defaulting to "delegable".
72
+ */
73
+ export const DELEGABLE_SUBJECT_TYPES = ['actor', 'link'];
74
+ /**
75
+ * THE ROLE THRESHOLD, DEFINED ONCE.
76
+ *
77
+ * `subject_min_role` is a floor over the existing four-value `org_role` enum
78
+ * and nothing more -- no custom roles, no nesting, no configurable inheritance.
79
+ * A `role` grant matches a principal holding `actual` iff this returns true; an
80
+ * `org` grant is the same question with `min = 'viewer'`.
81
+ *
82
+ * Both the point check (`getGroupGrants`) and the set query
83
+ * (`listAuthorizedFiles`) need this rule in SQL. Neither restates it: both are
84
+ * generated from `membershipCells()` below, which is generated from this
85
+ * function, exactly as the role matrix is generated from `fileCapabilities()`.
86
+ */
87
+ export function roleMeets(actual, min) {
88
+ return ROLE_RANK[actual] >= ROLE_RANK[min];
89
+ }
90
+ /**
91
+ * Every (floor, held) pair that satisfies `roleMeets`. 4 x 4 = 16 probes of a
92
+ * pure function; 10 cells survive. This is the whole group-membership rule, in
93
+ * a form SQL can test with a tuple `IN` list.
94
+ */
95
+ export function membershipCells() {
96
+ const cells = [];
97
+ for (const minRole of ALL_ROLES) {
98
+ for (const role of ALL_ROLES) {
99
+ if (roleMeets(role, minRole))
100
+ cells.push({ minRole, role });
101
+ }
102
+ }
103
+ return cells;
104
+ }
105
+ /**
106
+ * What each org role may do to a file in its own org.
107
+ *
108
+ * Deliberately small and total. Every cell is enumerated -- there is no
109
+ * fallthrough, no "and also if", no special case. A reviewer can read this
110
+ * table in ten seconds and know the entire role model, which is the point:
111
+ * an authorization model you cannot hold in your head is one you cannot audit.
112
+ *
113
+ * `visibility` closes the "every viewer in an org could read every file in it"
114
+ * defect. Under the default ('private') a file is not
115
+ * visible to the org at large at all; membership alone buys nothing at the file
116
+ * boundary. Org admins and owners keep full access under both settings, because
117
+ * retention, deletion and legal hold are their responsibility, and a control
118
+ * the accountable party cannot exercise is not a control.
119
+ */
120
+ export function fileCapabilities(role, isOwner, visibility) {
121
+ const none = new Set();
122
+ const readOnly = new Set(['read']);
123
+ const full = new Set(['read', 'write', 'delete', 'share']);
124
+ switch (role) {
125
+ case 'viewer':
126
+ // Viewers never do more than read, and under 'private' they read only
127
+ // what is theirs.
128
+ return isOwner || visibility === 'org' ? readOnly : none;
129
+ case 'member':
130
+ // Members fully control their own files, and may read others' in the org
131
+ // only when the file was created org-visible.
132
+ if (isOwner)
133
+ return full;
134
+ return visibility === 'org' ? readOnly : none;
135
+ case 'admin':
136
+ case 'owner':
137
+ return full;
138
+ }
139
+ }
140
+ /**
141
+ * What each org role may do to the organization itself.
142
+ *
143
+ * The same shape as the file table above, and enumerated for the same reason.
144
+ * `manage_members` is admin+: membership is the most powerful thing in the
145
+ * system, because it is the thing that confers everything else.
146
+ */
147
+ export function orgCapabilities(role) {
148
+ switch (role) {
149
+ case 'viewer':
150
+ return new Set();
151
+ case 'member':
152
+ return new Set(['create_file']);
153
+ case 'admin':
154
+ case 'owner':
155
+ return new Set(['create_file', 'manage_members', 'read_audit']);
156
+ }
157
+ }
158
+ /**
159
+ * Classify why a grant we can see is not live, for the audit log only.
160
+ *
161
+ * A grant that is self-consistent but still absent from `live_grant` is one
162
+ * whose ancestor chain is dead: that is P4 working, and the log should say so
163
+ * rather than reporting a forged secret.
164
+ */
165
+ function deadGrantReason(g, now) {
166
+ if (g.revokedAt)
167
+ return 'grant_revoked';
168
+ if (g.expiresAt && g.expiresAt <= now)
169
+ return 'grant_expired';
170
+ if (g.maxDownloads !== null && g.downloadCount >= g.maxDownloads)
171
+ return 'grant_exhausted';
172
+ return 'grant_ancestor_dead';
173
+ }
174
+ /**
175
+ * @param complete when true, consult every source of authority even after the
176
+ * requested capability has been found. The fast path stops as soon as it can
177
+ * answer the question asked, which is right for an access check and wrong for
178
+ * delegation: attenuation compares against everything the issuer holds, and a
179
+ * partially-resolved set would refuse to pass on authority the issuer really
180
+ * has. Only the share path pays for it.
181
+ */
182
+ async function resolveStanding(deps, principal, file, capability, now, complete = false) {
183
+ const capabilities = new Set();
184
+ const acc = {
185
+ via: null,
186
+ grant: null,
187
+ role: null,
188
+ };
189
+ /** Absorb a capability set; report whether it supplied the one we need. */
190
+ const take = (caps, path, g) => {
191
+ let got = false;
192
+ for (const c of caps) {
193
+ capabilities.add(c);
194
+ if (c === capability)
195
+ got = true;
196
+ }
197
+ if (got && acc.via === null) {
198
+ acc.via = path;
199
+ acc.grant = g;
200
+ }
201
+ return got;
202
+ };
203
+ const settled = (halt = null) => ({
204
+ recognised: capabilities.size > 0,
205
+ role: acc.role,
206
+ capabilities,
207
+ grant: acc.grant,
208
+ via: acc.via,
209
+ halt,
210
+ });
211
+ // --- org role -------------------------------------------------------------
212
+ if (principal.actorId) {
213
+ acc.role = await deps.getMembership(file.orgId, principal.actorId);
214
+ if (acc.role) {
215
+ const caps = fileCapabilities(acc.role, file.ownerId === principal.actorId, file.visibility);
216
+ if (take(caps, 'role', null) && !complete)
217
+ return settled();
218
+ }
219
+ // --- explicit actor grants ---------------------------------------------
220
+ // A member of the org without the capability may still hold an explicit
221
+ // grant, so we accumulate rather than deciding here.
222
+ const grants = await deps.getActorGrants(file.id, principal.actorId);
223
+ for (const g of grants) {
224
+ if (take(g.capabilities, 'grant:actor', g) && !complete)
225
+ return settled();
226
+ }
227
+ // --- group grants: 'org' and 'role' (RFC-001) --------------------------
228
+ // Consulted AFTER the actor grants, so a grant naming this person by name
229
+ // wins the `via` attribution over one that reaches them as part of a
230
+ // population. Both are ordinary grant rows; nothing here is a special case
231
+ // in liveness, revocation, delegation or capability handling.
232
+ //
233
+ // ONE EXTRA QUERY, resolved by JOIN. No fan-out, no materialized member
234
+ // list, nothing cached: add or remove a member and the very next call to
235
+ // this function sees it, with no grant row touched.
236
+ const groupGrants = await deps.getGroupGrants(file.id, principal.actorId);
237
+ for (const g of groupGrants) {
238
+ const path = g.subjectType === 'role' ? 'grant:role' : 'grant:org';
239
+ if (take(g.capabilities, path, g) && !complete)
240
+ return settled();
241
+ }
242
+ if (acc.via !== null && !complete)
243
+ return settled();
244
+ }
245
+ // --- link grants ----------------------------------------------------------
246
+ if (principal.linkSecret) {
247
+ const hash = await deps.hashSecret(principal.linkSecret);
248
+ const live = await deps.findLiveGrantBySecret(hash);
249
+ // The grant must belong to the file being requested. Without this check a
250
+ // valid link for file A would authorize file B -- the classic confused
251
+ // deputy. It is one line and it is the whole ballgame.
252
+ if (live && live.fileId === file.id) {
253
+ if (live.passwordHash) {
254
+ const ok = principal.password !== undefined &&
255
+ (await deps.verifyPassword(principal.password, live.passwordHash));
256
+ if (!ok)
257
+ return settled({ reason: 'bad_password', grantId: live.id });
258
+ }
259
+ if (take(live.capabilities, 'grant:link', live) && !complete)
260
+ return settled();
261
+ }
262
+ else if (!live) {
263
+ // Attribution only, never authorization: if the secret is real but the
264
+ // grant (or an ancestor of it) is dead, the log records which grant and
265
+ // why. This is what makes an exhausted or revoked link visible in the
266
+ // compliance record instead of looking like a forged one.
267
+ const any = await deps.findGrantBySecret(hash);
268
+ if (any && any.fileId === file.id) {
269
+ return settled({ reason: deadGrantReason(any, now), grantId: any.id });
270
+ }
271
+ }
272
+ }
273
+ // --- anonymous grants -----------------------------------------------------
274
+ // Note this is NOT a "public" flag on the file. It is an explicitly created,
275
+ // individually revocable, individually auditable grant row (P1). Anonymous
276
+ // grants are read-only by CHECK constraint, so there is nothing to look up
277
+ // when a stronger capability was asked for -- unless we are resolving the
278
+ // full set for delegation.
279
+ if (capability === 'read' || complete) {
280
+ const anon = await deps.getAnonymousGrant(file.id);
281
+ if (anon)
282
+ take(anon.capabilities, 'grant:anonymous', anon);
283
+ }
284
+ return settled();
285
+ }
286
+ /** The reason to report when a principal has no standing on a file at all. */
287
+ function noStandingReason(principal, role) {
288
+ if (principal.actorId)
289
+ return role ? 'insufficient_role' : 'no_membership';
290
+ if (principal.linkSecret)
291
+ return 'bad_link_secret';
292
+ return 'no_grant';
293
+ }
294
+ /**
295
+ * File lifecycle gates, in order of severity. Null means the file is usable.
296
+ *
297
+ * Retention holds block deletion even for org owners. This is the point of
298
+ * retention: it must bind the people who would otherwise be able to override
299
+ * it, or it is not a compliance control.
300
+ */
301
+ function lifecycleDenial(file, capability, now) {
302
+ if (file.state === 'deleted')
303
+ return 'file_deleted';
304
+ if (file.expiresAt && file.expiresAt <= now)
305
+ return 'file_expired';
306
+ if (file.state === 'pending' && capability === 'read')
307
+ return 'file_not_ready';
308
+ if (capability === 'delete' && file.retainUntil && file.retainUntil > now) {
309
+ return 'retention_hold';
310
+ }
311
+ return null;
312
+ }
313
+ /**
314
+ * The whole file-scoped decision, exactly once, emitting exactly one event.
315
+ * `authorize` and `authorizeShare` both run through here so that asking a
316
+ * second question about the same request cannot cost a second audit event or a
317
+ * second round of queries.
318
+ */
319
+ async function decideFile(deps, principal, fileId, capability, complete = false) {
320
+ const now = deps.now();
321
+ const file = await deps.getFile(fileId);
322
+ // --- 1. Existence ---------------------------------------------------------
323
+ // Audited against the SYSTEM chain: there is no tenant to charge an
324
+ // enumeration probe to, and inventing one would itself leak whether the file
325
+ // exists. Dropping the event -- which is what we used to do -- made a file-id
326
+ // sweep completely invisible.
327
+ if (!file) {
328
+ return {
329
+ decision: await deny(deps, null, principal, fileId, capability, 'file_not_found'),
330
+ file: null,
331
+ standing: null,
332
+ };
333
+ }
334
+ // --- 2. Standing ----------------------------------------------------------
335
+ const standing = await resolveStanding(deps, principal, file, capability, now, complete);
336
+ const out = (decision) => ({ decision, file, standing });
337
+ if (standing.halt) {
338
+ return out(await deny(deps, file.orgId, principal, fileId, capability, standing.halt.reason, standing.halt.grantId));
339
+ }
340
+ if (!standing.recognised) {
341
+ return out(await deny(deps, file.orgId, principal, fileId, capability, noStandingReason(principal, standing.role)));
342
+ }
343
+ // --- 3. Capability --------------------------------------------------------
344
+ if (!standing.capabilities.has(capability)) {
345
+ return out(await deny(deps, file.orgId, principal, fileId, capability, standing.role ? 'insufficient_role' : 'grant_wrong_capability'));
346
+ }
347
+ // --- 4. Lifecycle ---------------------------------------------------------
348
+ // Reached only by a caller who both has standing and holds the capability,
349
+ // so a 410 or a 409 here tells an attacker nothing they did not already have
350
+ // the authority to learn.
351
+ const lifecycle = lifecycleDenial(file, capability, now);
352
+ if (lifecycle) {
353
+ return out(await deny(deps, file.orgId, principal, fileId, capability, lifecycle, standing.grant?.id));
354
+ }
355
+ return out(await allow(deps, file.orgId, principal, fileId, capability, standing.via, standing.grant));
356
+ }
357
+ /** THE authorization decision. */
358
+ export async function authorize(deps, principal, fileId, capability) {
359
+ return (await decideFile(deps, principal, fileId, capability)).decision;
360
+ }
361
+ /**
362
+ * Derive the set predicate from the point-check functions.
363
+ *
364
+ * Pure, total, and cheap enough to call per request (28 function calls). It is
365
+ * called per request rather than memoised so that it cannot go stale against a
366
+ * hot-reloaded or monkey-patched role table.
367
+ */
368
+ export function listPredicate(capability) {
369
+ const roleCells = [];
370
+ for (const role of ALL_ROLES) {
371
+ for (const isOwner of [false, true]) {
372
+ for (const visibility of ALL_VISIBILITIES) {
373
+ if (fileCapabilities(role, isOwner, visibility).has(capability)) {
374
+ roleCells.push({ role, isOwner, visibility });
375
+ }
376
+ }
377
+ }
378
+ }
379
+ // A fixed reference clock: we are probing a pure function, not reading time.
380
+ const now = new Date(1_000_000);
381
+ const past = new Date(now.getTime() - 1000);
382
+ const future = new Date(now.getTime() + 1000);
383
+ const lifecycleCells = [];
384
+ for (const state of ALL_STATES) {
385
+ for (const expired of [false, true]) {
386
+ for (const retained of [false, true]) {
387
+ const probe = {
388
+ id: '',
389
+ orgId: '',
390
+ ownerId: null,
391
+ state,
392
+ visibility: 'private',
393
+ expiresAt: expired ? past : null,
394
+ retainUntil: retained ? future : null,
395
+ };
396
+ if (lifecycleDenial(probe, capability, now) === null) {
397
+ lifecycleCells.push({ state, expired, retained });
398
+ }
399
+ }
400
+ }
401
+ }
402
+ // Mirrors `resolveStanding`: the anonymous grant is consulted only for
403
+ // `read` on the access path. (Anonymous grants are read-only by CHECK, so
404
+ // this is belt and braces -- but the point check has the branch, so the set
405
+ // query must have it too or the two are not the same predicate.)
406
+ //
407
+ // Group grants have NO capability branch: unlike anonymous, they may carry
408
+ // any capability, so they are consulted for every capability -- which is
409
+ // exactly what `resolveStanding` does. The membership cells are the whole of
410
+ // the extra rule, and they are derived, not written.
411
+ return {
412
+ capability,
413
+ roleCells,
414
+ lifecycleCells,
415
+ membershipCells: membershipCells(),
416
+ anonymousEligible: capability === 'read',
417
+ };
418
+ }
419
+ /**
420
+ * THE set-scoped authorization decision.
421
+ *
422
+ * Note what this does NOT do: it does not gate on org membership before
423
+ * running the query. That would be a SECOND, different rule -- and it would be
424
+ * WRONG, because a grant may be issued to an actor who is not a member of the
425
+ * owning org at all. Such an actor's `authorize(read)` returns allow, so their
426
+ * `listFiles` must return that file, or the two disagree and the set query is
427
+ * not the access model.
428
+ *
429
+ * The empty set is therefore the correct answer for a caller with no standing,
430
+ * and it is also the answer for an org that does not exist. That symmetry is
431
+ * deliberate: a 404 for "no such org" against a 200 for "org you cannot see"
432
+ * would rebuild the existence oracle that the evaluation order closes.
433
+ *
434
+ * AUDIT: ONE event per call, not one per file. Reasoning in full, because it is
435
+ * a judgement call, and the reasons are recorded here:
436
+ *
437
+ * - The principal made ONE decision request and the engine evaluated ONE
438
+ * predicate. N events would describe an operation that did not happen: the
439
+ * caller did not access N files, they enumerated their own authorized set.
440
+ * - N events would put N hash-chain writes on the critical path of a read.
441
+ * The chain is serialized per org (see the chain-append note in store.ts),
442
+ * so a 200-row page would
443
+ * serialize 200 writes behind one lock. That is not a cost trade, it is an
444
+ * availability defect.
445
+ * - It would make unauthenticated chain flooding trivially worse: one
446
+ * request would append a page's worth of events.
447
+ * - A per-file loop would also emit a DENY for every file the caller may not
448
+ * see, which in a tenant with 100k files is 100k rows per listing screen.
449
+ *
450
+ * What is NOT given up: the event records the predicate (capability), the
451
+ * caller's role, the result cardinality and the returned ids, so "what did this
452
+ * principal learn the existence of, and when" is answerable from the log. And
453
+ * an empty result from a caller with no standing is recorded as a DENY with the
454
+ * same reason vocabulary the point check uses, so enumeration of a tenant by a
455
+ * non-member still shows up in a `decision = 'deny'` query.
456
+ */
457
+ export async function authorizeList(deps, principal, orgId, opts) {
458
+ const now = deps.now();
459
+ const exists = await deps.orgExists(orgId);
460
+ const role = exists && principal.actorId ? await deps.getMembership(orgId, principal.actorId) : null;
461
+ // One row over the page size, so "is there another page" costs nothing. A
462
+ // count(*) would have to evaluate the predicate over the whole tenant, which
463
+ // is both slow and a way to measure a tenant you cannot read.
464
+ //
465
+ // NOTE: the query runs whether or not `orgExists` said yes, and `exists` is
466
+ // used ONLY to decide which audit chain the event belongs to. Gating the
467
+ // query on it would be a precondition the point check does not have.
468
+ //
469
+ // This is where a stale-scope defect was found. `getMembership` joined `org` on
470
+ // `deleted_at IS NULL` and `getActorGrants` did not, so a soft-deleted org
471
+ // stopped conferring membership while leaving outstanding grants alive:
472
+ // `authorize()` still allowed a grant-holder to read those files, and a
473
+ // version of this function that skipped the query returned LESS than
474
+ // `authorize()` permitted. Fail-closed, and still a divergence, and the
475
+ // differential test caught it.
476
+ //
477
+ // That is now closed in the schema (`grant_scope_is_live`), so BOTH sides
478
+ // return nothing for a deleted org -- and they return nothing for the same
479
+ // reason, evaluated in the same predicate, rather than by two functions that
480
+ // happen to agree. The structure here is unchanged on purpose: `exists`
481
+ // still selects a chain and never gates a query.
482
+ const fetched = await deps.listAuthorizedFiles({
483
+ orgId,
484
+ actorId: principal.actorId,
485
+ predicate: listPredicate(opts.capability),
486
+ now,
487
+ limit: opts.limit + 1,
488
+ cursor: opts.cursor,
489
+ });
490
+ const hasMore = fetched.length > opts.limit;
491
+ const files = hasMore ? fetched.slice(0, opts.limit) : fetched;
492
+ const empty = files.length === 0;
493
+ await deps.audit({
494
+ // An org we cannot confirm goes to the system chain, exactly as
495
+ // `authorizeOrg` does, and for the same reason.
496
+ orgId: exists ? orgId : null,
497
+ action: 'file.list',
498
+ decision: empty ? 'deny' : 'allow',
499
+ ...(empty ? { reason: noStandingReason(principal, role) } : {}),
500
+ actorId: principal.actorId,
501
+ fileId: null,
502
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
503
+ ...(principal.userAgent !== undefined ? { userAgent: principal.userAgent } : {}),
504
+ context: {
505
+ ...(exists ? {} : { chain: 'system', orgId }),
506
+ capability: opts.capability,
507
+ role,
508
+ count: files.length,
509
+ fileIds: files.map((f) => f.id),
510
+ paged: opts.cursor !== null,
511
+ hasMore,
512
+ },
513
+ });
514
+ return { files, hasMore, role };
515
+ }
516
+ /**
517
+ * May this principal mint a grant on this file carrying these capabilities, to
518
+ * this kind of subject?
519
+ *
520
+ * Three questions, and all three belong here rather than in the API layer:
521
+ *
522
+ * 1. May they share at all?
523
+ * 2. Is what they are handing out a SUBSET of what they hold? (capability)
524
+ * 3. Is who they are handing it to no WIDER than they may reach? (I6, breadth)
525
+ *
526
+ * (2) used to live in `filelayer.share()`, which meant any second entry point
527
+ * built on `authorize()` silently reintroduced the escalation: a holder
528
+ * of `{share}` minting themselves `{delete}`. It is an authorization question,
529
+ * so the authorization engine answers it. The schema enforces the same rule
530
+ * again on the row itself, because a rule that exists only in application code
531
+ * binds only the application.
532
+ *
533
+ * (3) is the same argument in the other dimension, and it is new (RFC-001, I6).
534
+ * Attenuation over capabilities says what a delegate may DO; without a rule
535
+ * over subject breadth, a contractor holding one `{read, share}` grant could
536
+ * re-grant to an entire organization -- or to `anonymous` -- and every
537
+ * capability check would pass, because the child's set is a subset. Authority
538
+ * derived from an ORG ROLE (`via` of 'role' or 'owner') may name any subject;
539
+ * authority derived from a GRANT may name only an `actor` or mint a `link`.
540
+ *
541
+ * The engine refuses first, so the refusal is a decision with a reason and an
542
+ * audit event. The trigger in schema.sql refuses the same row again, so the
543
+ * rule holds for a caller issuing raw SQL. Same structure, same reasoning, as
544
+ * capability attenuation.
545
+ *
546
+ * -----------------------------------------------------------------------------
547
+ * KNOWN GAP, RECORDED RATHER THAN HIDDEN: `held` IS A UNION, `parentGrantId` IS
548
+ * ONE ROW.
549
+ * -----------------------------------------------------------------------------
550
+ * `held` is the union of every capability the issuer holds from every source,
551
+ * while `parentGrantId` is the SINGLE grant that supplied `share`. When a
552
+ * principal holds several grants on one file, the engine can therefore approve
553
+ * a capability set that no single ancestor covers -- and the attenuation
554
+ * trigger, which compares the child against its ONE parent, then refuses the
555
+ * INSERT. The outcome is a 403 rather than a disclosure, so the failure is
556
+ * fail-CLOSED and P4 is intact; what is wrong is that a legitimate delegation
557
+ * can be refused, and which one depends on the order the grants come back in.
558
+ *
559
+ * That order is now defined (`getActorGrants` sorts oldest-first) so the
560
+ * behaviour is at least deterministic and reproducible. Closing the gap
561
+ * properly means either picking the parent that covers the requested set, or
562
+ * minting one child per contributing ancestor, and both are changes to the
563
+ * delegation model rather than to this rule. Out of scope for RFC-001; flagged
564
+ * here so it is a decision rather than an accident.
565
+ */
566
+ export async function authorizeShare(deps, principal, fileId, requested, opts = {}) {
567
+ const resolved = await decideFile(deps, principal, fileId, 'share', true);
568
+ if (!resolved.decision.allow)
569
+ return { allow: false, reason: resolved.decision.reason };
570
+ const held = resolved.standing.capabilities;
571
+ for (const cap of requested) {
572
+ if (!held.has(cap)) {
573
+ await deps.audit({
574
+ orgId: resolved.file.orgId,
575
+ action: 'grant.create',
576
+ decision: 'deny',
577
+ reason: 'attenuation_violation',
578
+ actorId: principal.actorId,
579
+ fileId,
580
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
581
+ context: { requested: [...requested], held: [...held] },
582
+ });
583
+ return { allow: false, reason: 'attenuation_violation' };
584
+ }
585
+ }
586
+ // I6. `grantId` is set exactly when the authority that carried `share` came
587
+ // from a grant rather than from an org role -- it is the same value that
588
+ // becomes `parent_grant_id` below, which is what makes the engine's rule and
589
+ // the trigger's rule the same rule rather than two rules that agree.
590
+ const parentGrantId = resolved.decision.grantId ?? null;
591
+ const subjectType = opts.subjectType;
592
+ if (parentGrantId !== null &&
593
+ subjectType !== undefined &&
594
+ !DELEGABLE_SUBJECT_TYPES.includes(subjectType)) {
595
+ await deps.audit({
596
+ orgId: resolved.file.orgId,
597
+ action: 'grant.create',
598
+ decision: 'deny',
599
+ reason: 'subject_breadth_amplification',
600
+ actorId: principal.actorId,
601
+ fileId,
602
+ grantId: parentGrantId,
603
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
604
+ context: {
605
+ requestedSubjectType: subjectType,
606
+ via: resolved.decision.via,
607
+ delegableSubjectTypes: [...DELEGABLE_SUBJECT_TYPES],
608
+ },
609
+ });
610
+ return { allow: false, reason: 'subject_breadth_amplification' };
611
+ }
612
+ return {
613
+ allow: true,
614
+ via: resolved.decision.via,
615
+ // Authority derived from an org role has no parent grant; authority
616
+ // derived from a grant does, and the child is bound to it forever.
617
+ parentGrantId: resolved.decision.grantId ?? null,
618
+ held: [...held],
619
+ };
620
+ }
621
+ /**
622
+ * May this principal revoke this grant?
623
+ *
624
+ * Found during the review of the delegation work and fixed with it: holding
625
+ * `share` on a file used to mean holding revoke over EVERY grant on that file.
626
+ * A contractor given a delegated `{read, share}` could therefore revoke the
627
+ * owner's unrelated share links -- not a disclosure, but a straightforward
628
+ * denial of service against the file's other recipients, and a strange thing
629
+ * for "you may pass this on" to imply.
630
+ *
631
+ * The rule mirrors the delegation model rather than adding a new one:
632
+ *
633
+ * - authority from an org ROLE (admin, owner, or the file's own owner)
634
+ * carries revoke over every grant on the file, as before;
635
+ * - authority from a GRANT carries revoke only over that grant's own subtree,
636
+ * which is exactly the authority it was given.
637
+ */
638
+ export async function authorizeRevoke(deps, principal, grant) {
639
+ const resolved = await decideFile(deps, principal, grant.fileId, 'share');
640
+ if (!resolved.decision.allow)
641
+ return resolved.decision;
642
+ const via = resolved.decision.grantId ?? null;
643
+ if (via === null || grant.id === via || (await deps.isDescendantOf(via, grant.id))) {
644
+ return resolved.decision;
645
+ }
646
+ await deps.audit({
647
+ orgId: grant.orgId,
648
+ action: 'grant.revoke',
649
+ decision: 'deny',
650
+ reason: 'foreign_grant',
651
+ actorId: principal.actorId,
652
+ fileId: grant.fileId,
653
+ grantId: grant.id,
654
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
655
+ context: { viaGrantId: via },
656
+ });
657
+ return { allow: false, reason: 'foreign_grant' };
658
+ }
659
+ // =============================================================================
660
+ // THE ORG DECISION
661
+ // =============================================================================
662
+ export async function authorizeOrg(deps, principal, orgId, capability, opts = {}) {
663
+ const action = opts.action ?? `org.${capability}`;
664
+ const emitAllow = opts.emitAllow ?? true;
665
+ // An org we cannot see is audited to the system chain, for the same reason a
666
+ // file we cannot see is: attributing the event would confirm the org id, and
667
+ // the audit row's own foreign key would fail anyway.
668
+ const exists = await deps.orgExists(orgId);
669
+ if (!exists || !principal.actorId) {
670
+ return denyOrg(deps, exists ? orgId : null, principal, orgId, action, 'no_membership');
671
+ }
672
+ const role = await deps.getMembership(orgId, principal.actorId);
673
+ if (!role)
674
+ return denyOrg(deps, orgId, principal, orgId, action, 'no_membership');
675
+ if (!orgCapabilities(role).has(capability)) {
676
+ return denyOrg(deps, orgId, principal, orgId, action, 'insufficient_role');
677
+ }
678
+ if (emitAllow) {
679
+ await deps.audit({
680
+ orgId,
681
+ action,
682
+ decision: 'allow',
683
+ actorId: principal.actorId,
684
+ fileId: null,
685
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
686
+ ...(principal.userAgent !== undefined ? { userAgent: principal.userAgent } : {}),
687
+ context: { via: 'role', role, capability },
688
+ });
689
+ }
690
+ return { allow: true, via: 'role' };
691
+ }
692
+ /**
693
+ * May this principal set `targetActorId` to `newRole` (null = remove them)?
694
+ *
695
+ * Membership is the privilege that confers every other privilege, so the rules
696
+ * are stated here rather than left to the application:
697
+ *
698
+ * - you must hold `manage_members` (admin or owner);
699
+ * - you may not grant a role above your own -- otherwise `admin` is just
700
+ * `owner` with an extra step;
701
+ * - you may not modify anyone who currently outranks you;
702
+ * - you may not remove or demote the last owner, because an org nobody
703
+ * administers cannot honour a retention hold or a deletion request.
704
+ *
705
+ * Exactly one audit event is emitted per attempt, allow or deny. A membership
706
+ * change that leaves no trace is indistinguishable from a breach after the
707
+ * fact.
708
+ */
709
+ export async function authorizeMembershipChange(deps, principal, orgId, targetActorId, newRole) {
710
+ const orgReal = await deps.orgExists(orgId);
711
+ const currentRole = orgReal ? await deps.getMembership(orgId, targetActorId) : null;
712
+ const action = newRole === null ? 'member.remove' : currentRole === null ? 'member.add' : 'member.role_change';
713
+ const base = await authorizeOrg(deps, principal, orgId, 'manage_members', {
714
+ action,
715
+ emitAllow: false,
716
+ });
717
+ if (!base.allow)
718
+ return base;
719
+ const actorRole = (await deps.getMembership(orgId, principal.actorId));
720
+ const context = { targetActorId, fromRole: currentRole, toRole: newRole, byRole: actorRole };
721
+ const settle = async (reason) => {
722
+ await deps.audit({
723
+ orgId,
724
+ action,
725
+ decision: reason ? 'deny' : 'allow',
726
+ ...(reason ? { reason } : {}),
727
+ actorId: principal.actorId,
728
+ fileId: null,
729
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
730
+ ...(principal.userAgent !== undefined ? { userAgent: principal.userAgent } : {}),
731
+ context,
732
+ });
733
+ return reason ? { allow: false, reason } : { allow: true, via: 'role' };
734
+ };
735
+ if (currentRole !== null && ROLE_RANK[currentRole] > ROLE_RANK[actorRole]) {
736
+ return settle('superior_target');
737
+ }
738
+ if (newRole !== null && ROLE_RANK[newRole] > ROLE_RANK[actorRole]) {
739
+ return settle('role_escalation');
740
+ }
741
+ if (currentRole === 'owner' && newRole !== 'owner' && (await deps.countOwners(orgId)) <= 1) {
742
+ return settle('last_owner');
743
+ }
744
+ return settle(null);
745
+ }
746
+ // =============================================================================
747
+ // DECISION CORE -- the only places an access event is written
748
+ // =============================================================================
749
+ /**
750
+ * I4. For a group grant, "why did this succeed?" is not answered by `via`
751
+ * alone -- the caller is one of a population, and a compliance auditor needs to know
752
+ * which membership put them in it. The event already carries `actor_id` and
753
+ * `grant_id`, so the missing half is the subject org, the floor the grant
754
+ * asked for, and the role the caller actually held. All three come out of the
755
+ * membership join that already matched; none of them costs a second query.
756
+ */
757
+ function membershipContext(grant) {
758
+ if (!grant || grant.subjectOrgId === null)
759
+ return {};
760
+ return {
761
+ viaOrgId: grant.subjectOrgId,
762
+ viaMinRole: grant.subjectMinRole,
763
+ ...(grant.matchedRole !== undefined ? { viaRole: grant.matchedRole } : {}),
764
+ };
765
+ }
766
+ async function allow(deps, orgId, p, fileId, capability, via, grant) {
767
+ await deps.audit({
768
+ orgId,
769
+ action: `file.${capability}`,
770
+ decision: 'allow',
771
+ actorId: p.actorId,
772
+ fileId,
773
+ grantId: grant?.id ?? null,
774
+ ...(p.ip !== undefined ? { ip: p.ip } : {}),
775
+ ...(p.userAgent !== undefined ? { userAgent: p.userAgent } : {}),
776
+ context: { via, ...membershipContext(grant) },
777
+ });
778
+ return {
779
+ allow: true,
780
+ via,
781
+ ...(grant ? { grantId: grant.id } : {}),
782
+ remainingDownloads: grant == null || grant.maxDownloads == null ? null : grant.maxDownloads - grant.downloadCount,
783
+ };
784
+ }
785
+ async function deny(deps, orgId, p, fileId, capability, reason, grantId) {
786
+ await deps.audit({
787
+ orgId,
788
+ action: `file.${capability}`,
789
+ decision: 'deny',
790
+ reason,
791
+ actorId: p.actorId,
792
+ fileId,
793
+ grantId: grantId ?? null,
794
+ ...(p.ip !== undefined ? { ip: p.ip } : {}),
795
+ ...(p.userAgent !== undefined ? { userAgent: p.userAgent } : {}),
796
+ ...(orgId === null ? { context: { chain: 'system' } } : {}),
797
+ });
798
+ return { allow: false, reason };
799
+ }
800
+ async function denyOrg(deps, auditOrgId, p, orgId, action, reason) {
801
+ await deps.audit({
802
+ orgId: auditOrgId,
803
+ action,
804
+ decision: 'deny',
805
+ reason,
806
+ actorId: p.actorId,
807
+ fileId: null,
808
+ ...(p.ip !== undefined ? { ip: p.ip } : {}),
809
+ ...(p.userAgent !== undefined ? { userAgent: p.userAgent } : {}),
810
+ context: auditOrgId === null ? { chain: 'system', orgId } : { orgId },
811
+ });
812
+ return { allow: false, reason };
813
+ }
814
+ /**
815
+ * Emit an audit event for a decision that never reached the engine because the
816
+ * credential presented could not be resolved to anything at all -- a link
817
+ * secret matching no grant. There is no file and no tenant, so it goes to the
818
+ * system chain. A truncated hash of the presented secret is recorded so a
819
+ * brute-force sweep is correlatable; it is a 48-bit prefix of a SHA-256, not
820
+ * the credential, and it is useless without the original.
821
+ */
822
+ export async function auditUnresolvedSecret(deps, principal, secretHash) {
823
+ await deps.audit({
824
+ orgId: null,
825
+ action: 'file.read',
826
+ decision: 'deny',
827
+ reason: 'bad_link_secret',
828
+ actorId: principal.actorId,
829
+ fileId: null,
830
+ ...(principal.ip !== undefined ? { ip: principal.ip } : {}),
831
+ ...(principal.userAgent !== undefined ? { userAgent: principal.userAgent } : {}),
832
+ context: { chain: 'system', secretHashPrefix: secretHash.slice(0, 12) },
833
+ });
834
+ }
835
+ /**
836
+ * The refusals the schema raises on its own account (see the attenuation
837
+ * trigger in schema.sql).
838
+ *
839
+ * The engine refuses these cases first, so a trigger firing means the engine
840
+ * and the schema disagree -- which is a bug worth an alert, not a stack trace
841
+ * in a caller's face. The vocabulary lives here, next to the rules it mirrors,
842
+ * so that the two cannot drift apart in separate files.
843
+ */
844
+ const SCHEMA_REFUSAL = /^(grant_capability_amplification|grant_subject_amplification|grant_parent_not_live|grant_parent_exhausted|grant_parent_missing|grant_delegation_too_deep|grant_lineage_immutable)/;
845
+ export function schemaRefusal(err) {
846
+ const message = err instanceof Error ? err.message : String(err);
847
+ return SCHEMA_REFUSAL.test(message) ? message.split(':')[0] : null;
848
+ }
849
+ /**
850
+ * Collapse internal deny reasons into what the caller is told.
851
+ *
852
+ * Internally we record precisely why access was denied, because that is what
853
+ * makes the audit log useful for incident response. Externally we return 404
854
+ * for everything that would otherwise confirm a file's existence -- otherwise
855
+ * the error message becomes an enumeration oracle across tenants.
856
+ *
857
+ * Grant-level lifecycle reasons (revoked / expired / exhausted / ancestor dead)
858
+ * collapse to 404 as well. A 410 "your link is used up" would be friendlier and
859
+ * is reachable only by someone holding a 256-bit secret, so the leak is
860
+ * theoretical -- but it costs nothing to make a dead link indistinguishable
861
+ * from a forged one, and the audit log carries the true reason for the operator
862
+ * who actually needs it.
863
+ *
864
+ * The asymmetry between what we log and what we return is intentional and is
865
+ * the kind of decision a hand-rolled integration requires developers to make
866
+ * themselves, in every route, correctly, every time.
867
+ */
868
+ export function toPublicError(reason) {
869
+ switch (reason) {
870
+ case 'bad_password':
871
+ return { status: 401, code: 'password_required' };
872
+ case 'file_expired':
873
+ return { status: 410, code: 'gone' };
874
+ case 'retention_hold':
875
+ return { status: 409, code: 'retention_hold' };
876
+ // Attenuation and membership-management refusals are answered to a caller
877
+ // who has already proven standing and already knows the resource exists:
878
+ // 403 leaks nothing and is far more useful than a 404.
879
+ case 'attenuation_violation':
880
+ case 'subject_breadth_amplification':
881
+ case 'role_escalation':
882
+ case 'superior_target':
883
+ case 'last_owner':
884
+ return { status: 403, code: 'forbidden' };
885
+ default:
886
+ return { status: 404, code: 'not_found' };
887
+ }
888
+ }
889
+ //# sourceMappingURL=authz.js.map