@proteinjs/user 1.22.0 → 1.23.1

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.
@@ -8,6 +8,7 @@ import {
8
8
  getColumnByName,
9
9
  getDb,
10
10
  getDbAsSystem,
11
+ getDefaultTransactionContextFactory,
11
12
  getTables,
12
13
  withRecordColumns,
13
14
  Reference,
@@ -56,13 +57,51 @@ async function callerHasWriteAccess(
56
57
  permissionSourceTableName: string,
57
58
  on: { table: string; operation: string }
58
59
  ): Promise<boolean> {
60
+ const principal = requirePrincipal(on.table, on.operation);
61
+ const memo = transactionGrantMemo();
62
+ const key = `${principal}|${permissionSourceTableName}|${permissionSourceId}`;
63
+ const proven = memo?.get(key);
64
+ if (proven !== undefined) {
65
+ return proven;
66
+ }
59
67
  const qb = new QueryBuilder(tables.AccessGrant.name);
60
- qb.condition({ field: 'principal', operator: '=', value: requirePrincipal(on.table, on.operation) });
68
+ qb.condition({ field: 'principal', operator: '=', value: principal });
61
69
  qb.condition({ field: 'resource', operator: '=', value: permissionSourceId });
62
70
  qb.condition({ field: 'resourceTable', operator: '=', value: permissionSourceTableName });
63
71
  qb.condition({ field: 'accessLevel', operator: 'IN', value: WRITE_ACCESS_LEVELS });
64
72
  const grants = await getDbAsSystem<AccessGrant>().query(tables.AccessGrant, qb);
65
- return grants.length > 0;
73
+ const held = grants.length > 0;
74
+ memo?.set(key, held);
75
+ return held;
76
+ }
77
+
78
+ /**
79
+ * THE GRANTS ONE TRANSACTION HAS ALREADY PROVEN: {@link callerHasWriteAccess} is answered once per
80
+ * (principal, permission source) inside a transaction and reused for every later row of the same
81
+ * transaction — a transaction that attaches many rows to one scope (a document's whole subtree
82
+ * written in one unit) asks the grant table once, not once per row. Inside a read-write transaction
83
+ * every ask is a serial round trip, so the row count was the trip count. Keyed by the transaction's
84
+ * own object, a memo lives exactly as long as its transaction and never crosses one (a WeakMap,
85
+ * released with it). Outside a transaction nothing is memoized — every lone insert asks, as it
86
+ * always has.
87
+ *
88
+ * The one window the memo opens: a grant revoked inside the same transaction, after it was proven,
89
+ * is not asked again — the transaction's own earlier proof stands until it commits or aborts.
90
+ */
91
+ const grantsProvenInTransaction = new WeakMap<object, Map<string, boolean>>();
92
+
93
+ /** The current transaction's memo, created on first use; undefined outside a transaction. */
94
+ function transactionGrantMemo(): Map<string, boolean> | undefined {
95
+ const transaction = getDefaultTransactionContextFactory()?.getTransactionContext().currentTransaction;
96
+ if (!transaction || typeof transaction !== 'object') {
97
+ return undefined;
98
+ }
99
+ let memo = grantsProvenInTransaction.get(transaction);
100
+ if (!memo) {
101
+ memo = new Map();
102
+ grantsProvenInTransaction.set(transaction, memo);
103
+ }
104
+ return memo;
66
105
  }
67
106
 
68
107
  /**
@@ -23,14 +23,15 @@ export interface AccessInviteService<T extends Record> extends Service {
23
23
  /**
24
24
  * Creates an access invite for a resource. Caller must have admin access to the resource.
25
25
  * Returns a token and expiry which can be embedded as a query parameter in a shareable URL.
26
+ * The invite remembers the caller as its minter (`AccessInvite.createdBy`).
26
27
  */
27
28
  createAccessInvite(params: CreateAccessInviteParams): Promise<CreateAccessInviteResponse>;
28
29
  /**
29
30
  * Accepts an access invite using the provided token. The current authenticated user's grant on
30
31
  * the resource is reconciled up to the invite's access level (created when absent, upgraded when
31
- * lower — never downgraded or duplicated). Invite links are multi-use: any number of holders can
32
- * accept until the token expires, and re-accepting is idempotent. Throws only for an unknown or
33
- * expired token.
32
+ * lower — never downgraded or duplicated), and names the invite's minter as the one who conferred
33
+ * it (`AccessGrant.grantedBy`). Invite links are multi-use: any number of holders can accept until
34
+ * the token expires, and re-accepting is idempotent. Throws only for an unknown or expired token.
34
35
  */
35
36
  acceptAccessInvite(token: string): Promise<T | undefined>;
36
37
  }
@@ -20,6 +20,14 @@ export type AccessGrant = Record & {
20
20
  resource: Reference<any>;
21
21
  resourceTable?: Table<any>['name'];
22
22
  accessLevel: 'read' | 'write' | 'admin' | 'owner';
23
+ /**
24
+ * WHO CONFERRED THIS GRANT — the stored "shared with you by". A grant conferred through an invite
25
+ * carries the invite's MINTER (copied at the accept, never the acceptor); a grant a caller inserts
26
+ * directly carries that caller (a direct share, a re-level); the grant the system confers with no
27
+ * one behind it — the creator's own owner grant at a shared record's birth — carries nobody.
28
+ * `created` beside it is the "when".
29
+ */
30
+ grantedBy?: Reference<any>;
23
31
  };
24
32
 
25
33
  /**
@@ -105,6 +113,20 @@ export class AccessGrantTable extends Table<AccessGrant> {
105
113
  onBeforeInsert: async (_table, insertObj: AccessGrant) => this.assertWellFormed(insertObj),
106
114
  }),
107
115
  resource: new DynamicReferenceColumn<any>('resource', 'resource_table', false),
116
+ // The granter, stamped at the table so EVERY direct road carries it — a caller's insert names the
117
+ // caller; a system insert keeps whatever the writer set (the accept copies the invite's minter;
118
+ // the shared-record bootstrap sets nothing, and nothing is what the creator's own grant carries).
119
+ grantedBy: new ReferenceColumn<User>('granted_by', 'user', false, {
120
+ onBeforeInsert: async (_table, insertObj: AccessGrant, runAsSystem) => {
121
+ if (runAsSystem || insertObj.grantedBy?._id) {
122
+ return;
123
+ }
124
+ const callerId = new UserRepo().getUser().id;
125
+ if (callerId) {
126
+ insertObj.grantedBy = new Reference<User>('user', callerId);
127
+ }
128
+ },
129
+ }),
108
130
  resourceTable: new DynamicReferenceTableNameColumn('resource_table', 'resource', {
109
131
  onBeforeInsert: async (_table, insertObj: AccessGrant, runAsSystem) => {
110
132
  if (runAsSystem) {
@@ -29,6 +29,14 @@ export type AccessInvite<T extends Record = any> = Record & {
29
29
  accepted?: boolean;
30
30
  acceptedBy?: Reference<User>;
31
31
  acceptedAt?: Moment;
32
+ /**
33
+ * THE MINTER — the account that created this invite, stamped from the caller at the mint. The one
34
+ * durable "who shared this": an accepted invite copies it onto the grant it confers
35
+ * (`AccessGrant.grantedBy`), so a recipient's grant names the person who sent the link, never the
36
+ * last account that happened to open a multi-use link (the telemetry above). Absent only on a
37
+ * system mint with no caller behind it.
38
+ */
39
+ createdBy?: Reference<User>;
32
40
  };
33
41
 
34
42
  export class AccessInviteTable extends Table<AccessInvite> {
@@ -50,6 +58,19 @@ export class AccessInviteTable extends Table<AccessInvite> {
50
58
  accepted: new BooleanColumn('accepted', { defaultValue: async () => false }),
51
59
  acceptedBy: new ReferenceColumn('accepted_by', new UserTable().name, false),
52
60
  acceptedAt: new DateTimeColumn('accepted_at'),
61
+ // The minter, stamped at the table so EVERY mint road carries it — a caller's insert names the
62
+ // caller; a system insert keeps whatever the writer set (nothing, when no one is behind it).
63
+ createdBy: new ReferenceColumn('created_by', new UserTable().name, false, {
64
+ onBeforeInsert: async (_table, insertObj: AccessInvite, runAsSystem) => {
65
+ if (runAsSystem || insertObj.createdBy?._id) {
66
+ return;
67
+ }
68
+ const callerId = new UserRepo().getUser().id;
69
+ if (callerId) {
70
+ insertObj.createdBy = new Reference<User>(new UserTable().name, callerId);
71
+ }
72
+ },
73
+ }),
53
74
  accessLevel: new StringColumn('access_level'),
54
75
  resource: new DynamicReferenceColumn('resource', 'resource_table'),
55
76
  resourceTable: new DynamicReferenceTableNameColumn('resource_table', 'resource', {