@happyvertical/smrt-users 0.42.3 → 0.42.5
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.
- package/dist/chunks/{TerminalAuthService-Bg3s5wHA.js → TerminalAuthService-CAomvhMa.js} +449 -254
- package/dist/chunks/TerminalAuthService-CAomvhMa.js.map +1 -0
- package/dist/collections/CliAuthApproveLimitCollection.d.ts +24 -0
- package/dist/collections/CliAuthApproveLimitCollection.d.ts.map +1 -0
- package/dist/collections/CliAuthRequestCollection.d.ts +35 -1
- package/dist/collections/CliAuthRequestCollection.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +346 -60
- package/dist/models/CliAuthApproveLimit.d.ts +11 -0
- package/dist/models/CliAuthApproveLimit.d.ts.map +1 -0
- package/dist/models/CliAuthRequest.d.ts +6 -6
- package/dist/models/CliAuthRequest.d.ts.map +1 -1
- package/dist/retention.d.ts.map +1 -1
- package/dist/services/TerminalAuthService.d.ts +9 -11
- package/dist/services/TerminalAuthService.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +146 -16
- package/dist/sveltekit.js +1 -1
- package/package.json +10 -10
- package/dist/chunks/TerminalAuthService-Bg3s5wHA.js.map +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { SmrtObject } from '@happyvertical/smrt-core';
|
|
2
|
+
/** Private database arbiter shared by every terminal-auth process. */
|
|
3
|
+
export declare class UsersCliAuthApproveLimit extends SmrtObject {
|
|
4
|
+
/** Approving browser user whose budget this row protects. */
|
|
5
|
+
userId: string;
|
|
6
|
+
/** Failed attempts plus currently reserved attempts inside the window. */
|
|
7
|
+
attemptCount: number;
|
|
8
|
+
/** Beginning of the current failed-attempt window. */
|
|
9
|
+
windowStartedAt: Date;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=CliAuthApproveLimit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CliAuthApproveLimit.d.ts","sourceRoot":"","sources":["../../src/models/CliAuthApproveLimit.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAqB,UAAU,EAAQ,MAAM,0BAA0B,CAAC;AAE/E,sEAAsE;AACtE,qBAMa,wBAAyB,SAAQ,UAAU;IACtD,6DAA6D;IAE7D,MAAM,SAAM;IAEZ,0EAA0E;IAE1E,YAAY,SAAK;IAEjB,sDAAsD;IAEtD,eAAe,OAAc;CAC9B"}
|
|
@@ -2,7 +2,7 @@ import { SmrtObject } from '@happyvertical/smrt-core';
|
|
|
2
2
|
/**
|
|
3
3
|
* CLI auth request lifecycle states.
|
|
4
4
|
*/
|
|
5
|
-
export type CliAuthRequestStatus = 'pending' | 'approved' | 'expired';
|
|
5
|
+
export type CliAuthRequestStatus = 'pending' | 'approved' | 'consumed' | 'expired';
|
|
6
6
|
export declare class UsersCliAuthRequest extends SmrtObject {
|
|
7
7
|
/**
|
|
8
8
|
* Short, human-typeable code the user enters in the browser to approve the session.
|
|
@@ -18,14 +18,14 @@ export declare class UsersCliAuthRequest extends SmrtObject {
|
|
|
18
18
|
* up by this column (#2364, epic #2382 finding A3).
|
|
19
19
|
*/
|
|
20
20
|
deviceCodeHash: string;
|
|
21
|
-
/** Lifecycle state — `pending` → `approved`
|
|
21
|
+
/** Lifecycle state — `pending` → `approved` → `consumed`, or `expired`. */
|
|
22
22
|
status: CliAuthRequestStatus;
|
|
23
23
|
/** User id of the human who approved the request (set on approval). */
|
|
24
|
-
userId: string;
|
|
24
|
+
userId: string | null;
|
|
25
25
|
/** Tenant id captured from the approving session (set on approval). */
|
|
26
|
-
tenantId: string;
|
|
27
|
-
/** Session id minted on approval
|
|
28
|
-
sessionId: string;
|
|
26
|
+
tenantId: string | null;
|
|
27
|
+
/** Session id minted on approval; cleared by the winning single-use exchange. */
|
|
28
|
+
sessionId: string | null;
|
|
29
29
|
/**
|
|
30
30
|
* When the pending request stops accepting approvals.
|
|
31
31
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CliAuthRequest.d.ts","sourceRoot":"","sources":["../../src/models/CliAuthRequest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,
|
|
1
|
+
{"version":3,"file":"CliAuthRequest.d.ts","sourceRoot":"","sources":["../../src/models/CliAuthRequest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAqB,UAAU,EAAQ,MAAM,0BAA0B,CAAC;AAE/E;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAC5B,SAAS,GACT,UAAU,GACV,UAAU,GACV,SAAS,CAAC;AAEd,qBAMa,mBAAoB,SAAQ,UAAU;IACjD;;;;;OAKG;IAEH,QAAQ,SAAM;IAEd;;;;;OAKG;IAEH,cAAc,SAAM;IAEpB,2EAA2E;IAE3E,MAAM,EAAE,oBAAoB,CAAa;IAEzC,uEAAuE;IAEvE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE7B,uEAAuE;IAEvE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE/B,iFAAiF;IAEjF,SAAS,EAAE,MAAM,GAAG,IAAI,CAAQ;IAEhC;;;;;OAKG;IAEH,SAAS,OAAc;IAEvB,wEAAwE;IAExE,UAAU,EAAE,IAAI,GAAG,IAAI,CAAQ;CAChC;AAED,OAAO,EAAE,mBAAmB,IAAI,cAAc,EAAE,CAAC"}
|
package/dist/retention.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retention.d.ts","sourceRoot":"","sources":["../src/retention.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAUH,4DAA4D;AAC5D,eAAO,MAAM,uBAAuB,mBAAmB,CAAC;AAExD,yDAAyD;AACzD,eAAO,MAAM,yBAAyB,4BAA4B,CAAC;AAEnE,gEAAgE;AAChE,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AAEjE,mEAAmE;AACnE,eAAO,MAAM,oBAAoB,mFAIvB,CAAC;AAEX;;;;;;;;;;GAUG;AACH,wBAAgB,0BAA0B,IAAI,IAAI,
|
|
1
|
+
{"version":3,"file":"retention.d.ts","sourceRoot":"","sources":["../src/retention.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAUH,4DAA4D;AAC5D,eAAO,MAAM,uBAAuB,mBAAmB,CAAC;AAExD,yDAAyD;AACzD,eAAO,MAAM,yBAAyB,4BAA4B,CAAC;AAEnE,gEAAgE;AAChE,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AAEjE,mEAAmE;AACnE,eAAO,MAAM,oBAAoB,mFAIvB,CAAC;AAEX;;;;;;;;;;GAUG;AACH,wBAAgB,0BAA0B,IAAI,IAAI,CA4BjD;AAED,sEAAsE;AACtE,wBAAgB,4BAA4B,IAAI,IAAI,CAInD"}
|
|
@@ -107,7 +107,8 @@ export declare class TerminalAuthService {
|
|
|
107
107
|
private readonly verificationPath;
|
|
108
108
|
private readonly maxApproveAttempts;
|
|
109
109
|
private readonly approveAttemptWindowMs;
|
|
110
|
-
private readonly
|
|
110
|
+
private readonly approveQueuesByUser;
|
|
111
|
+
private approveLimitCollection;
|
|
111
112
|
private requestCollection;
|
|
112
113
|
private sessionService;
|
|
113
114
|
constructor(options: TerminalAuthServiceOptions);
|
|
@@ -115,10 +116,9 @@ export declare class TerminalAuthService {
|
|
|
115
116
|
static create(options: TerminalAuthServiceOptions): Promise<TerminalAuthService>;
|
|
116
117
|
private makeUserCode;
|
|
117
118
|
/**
|
|
118
|
-
* Generate a user code that is not
|
|
119
|
-
* (
|
|
120
|
-
*
|
|
121
|
-
* affected CLI from being locked out.
|
|
119
|
+
* Generate a user code that is not present in durable request history.
|
|
120
|
+
* Collisions are vanishingly rare (1 in 2^32 per attempt) but happen at
|
|
121
|
+
* scale; retrying keeps the affected CLI from being locked out.
|
|
122
122
|
*/
|
|
123
123
|
private makeUniqueUserCode;
|
|
124
124
|
/**
|
|
@@ -140,12 +140,10 @@ export declare class TerminalAuthService {
|
|
|
140
140
|
*/
|
|
141
141
|
approveRequest(input: ApproveCliAuthRequestInput): Promise<UsersCliAuthRequest>;
|
|
142
142
|
/**
|
|
143
|
-
*
|
|
144
|
-
*
|
|
143
|
+
* Serialize approval attempts per user so parallel requests cannot all pass
|
|
144
|
+
* the failed-attempt check before any one of them records its failure.
|
|
145
145
|
*/
|
|
146
|
-
private
|
|
147
|
-
/** Increment the failed-approve counter for `userId`, starting the window if needed. */
|
|
148
|
-
private recordFailedApprove;
|
|
146
|
+
private withSerializedApprove;
|
|
149
147
|
/**
|
|
150
148
|
* Exchange a device code (the secret the CLI keeps) for an access token
|
|
151
149
|
* once the request has been approved. Returns `{ status: 'pending' }` while
|
|
@@ -165,7 +163,7 @@ export declare class TerminalAuthService {
|
|
|
165
163
|
*/
|
|
166
164
|
destroyBearerSession(token: string): Promise<boolean>;
|
|
167
165
|
/**
|
|
168
|
-
* Delete expired pending requests (cleanup job).
|
|
166
|
+
* Delete expired pending or already-consumed requests (cleanup job).
|
|
169
167
|
*/
|
|
170
168
|
cleanupExpiredRequests(): Promise<number>;
|
|
171
169
|
/** The default polling interval clients should use. Exposed for tests. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TerminalAuthService.d.ts","sourceRoot":"","sources":["../../src/services/TerminalAuthService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"TerminalAuthService.d.ts","sourceRoot":"","sources":["../../src/services/TerminalAuthService.ts"],"names":[],"mappings":"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"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-users",
|
|
6
|
-
"packageVersion": "0.42.
|
|
6
|
+
"packageVersion": "0.42.5",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
10
|
+
"manifest": "b4e533246de730c6dd79b183a14d14239f13faeb5e12b7caf2f6867cca7302a5",
|
|
11
|
+
"packageJson": "0d201d59da87fbbef7807f26bc7fbb2c51ea7de7af6b9f83d3ff6906676d1850",
|
|
12
12
|
"agents": "6ec265b8af7cdfa9fea1a3f128af9bf25cbcdb1353c34a81a7fc5b0d2e4a8f2b",
|
|
13
|
-
"moduleDoc:agents/retention.md": "
|
|
13
|
+
"moduleDoc:agents/retention.md": "425c0a34ed33969badfef699751bfa670bdf618eda65e079e00815620aabed68"
|
|
14
14
|
},
|
|
15
15
|
"exports": [
|
|
16
16
|
".",
|
|
@@ -113,6 +113,45 @@
|
|
|
113
113
|
"tags": [],
|
|
114
114
|
"risks": []
|
|
115
115
|
},
|
|
116
|
+
{
|
|
117
|
+
"name": "UsersCliAuthApproveLimitCollection",
|
|
118
|
+
"qualifiedName": "@happyvertical/smrt-users:UsersCliAuthApproveLimitCollection",
|
|
119
|
+
"collection": "userscliauthapprovelimits",
|
|
120
|
+
"tableName": "users_cli_auth_approve_limits",
|
|
121
|
+
"packageName": "@happyvertical/smrt-users",
|
|
122
|
+
"extends": "SmrtCollection",
|
|
123
|
+
"fields": [],
|
|
124
|
+
"relationships": [],
|
|
125
|
+
"methods": [
|
|
126
|
+
"releaseAttempt",
|
|
127
|
+
"reserveAttempt"
|
|
128
|
+
],
|
|
129
|
+
"methodSignatures": [
|
|
130
|
+
{
|
|
131
|
+
"name": "releaseAttempt",
|
|
132
|
+
"async": true,
|
|
133
|
+
"params": [
|
|
134
|
+
"userId: string",
|
|
135
|
+
"windowStartedAt: string"
|
|
136
|
+
],
|
|
137
|
+
"returns": "Promise<void>"
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
"name": "reserveAttempt",
|
|
141
|
+
"async": true,
|
|
142
|
+
"params": [
|
|
143
|
+
"input: object"
|
|
144
|
+
],
|
|
145
|
+
"returns": "Promise<CliAuthApproveReservation>"
|
|
146
|
+
}
|
|
147
|
+
],
|
|
148
|
+
"surfaces": [],
|
|
149
|
+
"relationshipFeatures": [
|
|
150
|
+
"uuidColumns"
|
|
151
|
+
],
|
|
152
|
+
"tags": [],
|
|
153
|
+
"risks": []
|
|
154
|
+
},
|
|
116
155
|
{
|
|
117
156
|
"name": "UsersCliAuthRequestCollection",
|
|
118
157
|
"qualifiedName": "@happyvertical/smrt-users:UsersCliAuthRequestCollection",
|
|
@@ -123,11 +162,29 @@
|
|
|
123
162
|
"fields": [],
|
|
124
163
|
"relationships": [],
|
|
125
164
|
"methods": [
|
|
165
|
+
"approvePendingRequest",
|
|
166
|
+
"consumeApprovedSession",
|
|
126
167
|
"deleteExpired",
|
|
127
168
|
"findByDeviceCodeHash",
|
|
128
169
|
"findByUserCode"
|
|
129
170
|
],
|
|
130
171
|
"methodSignatures": [
|
|
172
|
+
{
|
|
173
|
+
"name": "approvePendingRequest",
|
|
174
|
+
"async": true,
|
|
175
|
+
"params": [
|
|
176
|
+
"input: ApprovePendingCliAuthRequestInput"
|
|
177
|
+
],
|
|
178
|
+
"returns": "Promise<ApprovedCliAuthRequestSnapshot | null>"
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
"name": "consumeApprovedSession",
|
|
182
|
+
"async": true,
|
|
183
|
+
"params": [
|
|
184
|
+
"deviceCodeHash: string"
|
|
185
|
+
],
|
|
186
|
+
"returns": "Promise<string | null>"
|
|
187
|
+
},
|
|
131
188
|
{
|
|
132
189
|
"name": "deleteExpired",
|
|
133
190
|
"async": true,
|
|
@@ -1590,6 +1647,53 @@
|
|
|
1590
1647
|
"tags": [],
|
|
1591
1648
|
"risks": []
|
|
1592
1649
|
},
|
|
1650
|
+
{
|
|
1651
|
+
"name": "UsersCliAuthApproveLimit",
|
|
1652
|
+
"qualifiedName": "@happyvertical/smrt-users:UsersCliAuthApproveLimit",
|
|
1653
|
+
"collection": "userscliauthapprovelimits",
|
|
1654
|
+
"tableName": "users_cli_auth_approve_limits",
|
|
1655
|
+
"packageName": "@happyvertical/smrt-users",
|
|
1656
|
+
"extends": "SmrtObject",
|
|
1657
|
+
"fields": [
|
|
1658
|
+
{
|
|
1659
|
+
"name": "userId",
|
|
1660
|
+
"type": "foreignKey",
|
|
1661
|
+
"required": true,
|
|
1662
|
+
"related": "User",
|
|
1663
|
+
"columnType": "UUID"
|
|
1664
|
+
},
|
|
1665
|
+
{
|
|
1666
|
+
"name": "attemptCount",
|
|
1667
|
+
"type": "integer",
|
|
1668
|
+
"required": true,
|
|
1669
|
+
"columnType": "INTEGER",
|
|
1670
|
+
"default": 0
|
|
1671
|
+
},
|
|
1672
|
+
{
|
|
1673
|
+
"name": "windowStartedAt",
|
|
1674
|
+
"type": "datetime",
|
|
1675
|
+
"required": true,
|
|
1676
|
+
"columnType": "TIMESTAMP"
|
|
1677
|
+
}
|
|
1678
|
+
],
|
|
1679
|
+
"relationships": [
|
|
1680
|
+
{
|
|
1681
|
+
"name": "userId",
|
|
1682
|
+
"type": "foreignKey",
|
|
1683
|
+
"required": true,
|
|
1684
|
+
"related": "User",
|
|
1685
|
+
"columnType": "UUID"
|
|
1686
|
+
}
|
|
1687
|
+
],
|
|
1688
|
+
"methods": [],
|
|
1689
|
+
"surfaces": [],
|
|
1690
|
+
"relationshipFeatures": [
|
|
1691
|
+
"foreignKey",
|
|
1692
|
+
"uuidColumns"
|
|
1693
|
+
],
|
|
1694
|
+
"tags": [],
|
|
1695
|
+
"risks": []
|
|
1696
|
+
},
|
|
1593
1697
|
{
|
|
1594
1698
|
"name": "UsersCliAuthRequest",
|
|
1595
1699
|
"qualifiedName": "@happyvertical/smrt-users:UsersCliAuthRequest",
|
|
@@ -1601,13 +1705,13 @@
|
|
|
1601
1705
|
{
|
|
1602
1706
|
"name": "userCode",
|
|
1603
1707
|
"type": "text",
|
|
1604
|
-
"required":
|
|
1708
|
+
"required": true,
|
|
1605
1709
|
"columnType": "TEXT"
|
|
1606
1710
|
},
|
|
1607
1711
|
{
|
|
1608
1712
|
"name": "deviceCodeHash",
|
|
1609
1713
|
"type": "text",
|
|
1610
|
-
"required":
|
|
1714
|
+
"required": true,
|
|
1611
1715
|
"columnType": "TEXT"
|
|
1612
1716
|
},
|
|
1613
1717
|
{
|
|
@@ -1618,21 +1722,24 @@
|
|
|
1618
1722
|
},
|
|
1619
1723
|
{
|
|
1620
1724
|
"name": "userId",
|
|
1621
|
-
"type": "
|
|
1725
|
+
"type": "foreignKey",
|
|
1622
1726
|
"required": false,
|
|
1623
|
-
"
|
|
1727
|
+
"related": "User",
|
|
1728
|
+
"columnType": "UUID"
|
|
1624
1729
|
},
|
|
1625
1730
|
{
|
|
1626
1731
|
"name": "tenantId",
|
|
1627
|
-
"type": "
|
|
1732
|
+
"type": "foreignKey",
|
|
1628
1733
|
"required": false,
|
|
1629
|
-
"
|
|
1734
|
+
"related": "Tenant",
|
|
1735
|
+
"columnType": "UUID"
|
|
1630
1736
|
},
|
|
1631
1737
|
{
|
|
1632
1738
|
"name": "sessionId",
|
|
1633
|
-
"type": "
|
|
1739
|
+
"type": "foreignKey",
|
|
1634
1740
|
"required": false,
|
|
1635
|
-
"
|
|
1741
|
+
"related": "Session",
|
|
1742
|
+
"columnType": "UUID"
|
|
1636
1743
|
},
|
|
1637
1744
|
{
|
|
1638
1745
|
"name": "expiresAt",
|
|
@@ -1647,10 +1754,33 @@
|
|
|
1647
1754
|
"columnType": "TIMESTAMP"
|
|
1648
1755
|
}
|
|
1649
1756
|
],
|
|
1650
|
-
"relationships": [
|
|
1757
|
+
"relationships": [
|
|
1758
|
+
{
|
|
1759
|
+
"name": "userId",
|
|
1760
|
+
"type": "foreignKey",
|
|
1761
|
+
"required": false,
|
|
1762
|
+
"related": "User",
|
|
1763
|
+
"columnType": "UUID"
|
|
1764
|
+
},
|
|
1765
|
+
{
|
|
1766
|
+
"name": "tenantId",
|
|
1767
|
+
"type": "foreignKey",
|
|
1768
|
+
"required": false,
|
|
1769
|
+
"related": "Tenant",
|
|
1770
|
+
"columnType": "UUID"
|
|
1771
|
+
},
|
|
1772
|
+
{
|
|
1773
|
+
"name": "sessionId",
|
|
1774
|
+
"type": "foreignKey",
|
|
1775
|
+
"required": false,
|
|
1776
|
+
"related": "Session",
|
|
1777
|
+
"columnType": "UUID"
|
|
1778
|
+
}
|
|
1779
|
+
],
|
|
1651
1780
|
"methods": [],
|
|
1652
1781
|
"surfaces": [],
|
|
1653
1782
|
"relationshipFeatures": [
|
|
1783
|
+
"foreignKey",
|
|
1654
1784
|
"uuidColumns"
|
|
1655
1785
|
],
|
|
1656
1786
|
"tags": [],
|
|
@@ -4656,19 +4786,19 @@
|
|
|
4656
4786
|
],
|
|
4657
4787
|
"prompts": [],
|
|
4658
4788
|
"relationshipsV2": {
|
|
4659
|
-
"foreignKeyFields":
|
|
4789
|
+
"foreignKeyFields": 22,
|
|
4660
4790
|
"crossPackageRefFields": 1,
|
|
4661
4791
|
"junctionCollections": 0,
|
|
4662
4792
|
"hierarchicalObjects": 0,
|
|
4663
4793
|
"polymorphicAssociations": 0,
|
|
4664
|
-
"uuidColumns":
|
|
4794
|
+
"uuidColumns": 58
|
|
4665
4795
|
},
|
|
4666
4796
|
"agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Modules\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/retention.ts` | expired session/token/CLI-auth reaping and its wiring into the framework retention sweep | [agents/retention.md](agents/retention.md) |\n\n## Models (14)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is a unique cross-package reference to smrt-profiles (one User per non-null Profile). Email auto-lowercased; readonly nullable unique `emailKey` is derived on save for durable normalized uniqueness. |\n| AccessRequest | \"Request access / waitlist\" record captured before a `User` exists. CLOSED generated surface (`api`/`mcp`/`cli` = `[]`) — all access via `AccessRequestService`. Email normalized + indexed; JSON `requestContext` (NOT `context` — reserved for slug scoping). |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. `inheritsToDescendants: true` (default false) opts the role's membership authority into descendant tenants. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n### Membership selection — hierarchical inheritance (opt-in, #1866)\n\nWhich membership feeds step 2 above:\n\n1. **A direct membership row in the target tenant always pins resolution to\n itself** — active rows resolve normally; an inactive (pending/suspended)\n row resolves to the **empty set**. A direct row therefore *attenuates*\n rather than unions: \"viewer here, despite being network admin\" gives\n viewer, and a suspension in the child is effective even for users holding\n inheritable authority on an ancestor.\n2. **No direct row** → the resolver walks the tenant's ancestors (nearest\n first, from `hierarchyPath`) and resolves through the **nearest ACTIVE\n ancestor membership whose role has `inheritsToDescendants: true`**.\n Unflagged or inactive ancestor memberships are skipped (they neither confer\n nor block); there is **no union across the chain** — the nearest flagged\n membership alone is used. To attenuate a specific descendant, create a\n direct membership there or use a tenant-level DENY.\n3. **No qualifying ancestor** → empty set (byte-identical to the\n pre-inheritance resolver; with no role flagged, nothing changes).\n\nAll later layers run unchanged against the **target** tenant: the tenant\ncascade and tenant-DENY hard block come from the target tenant (a child can\ncarve authority out of an inherited role), group roles stay exact-tenant (only\ntarget-tenant groups contribute; ancestor groups never flow down), and\nmembership GRANT/DENY overrides travel with the ancestor membership used.\n`PermissionResolutionResult.inheritedFromTenantId` reports the ancestor tenant\nwhen inheritance was used (`null` for direct resolution).\n\nSafety: resolution is bounded by `MAX_TENANT_HIERARCHY_DEPTH`; malformed\n`hierarchyPath` values fail closed to the empty set — too deep,\nself-referential, duplicate ancestors, or inconsistent with the actual\n`parentTenantId` chain (the path is verified link-by-link against the loaded\nancestor rows before it is trusted as an authorization source). Tenant `status` is not consulted (parity with direct\nresolution). Caching: a long-lived `(user, tenant)` permission cache must also\ninvalidate on ancestor-membership changes and on `Role.inheritsToDescendants`\nflips — request-scoped caches (the common pattern) are unaffected.\n\nFlag roles at seed time with\n`seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] })` (additive:\nlisted slugs are flagged, omitted slugs are never unflagged; unknown slugs\nthrow). The default seed leaves every role exact-tenant.\n\n## Operation Permission Guards\n\nSMRT derives a fine-grained, per-`<collection>.<action>` permission catalog **from the\nmanifest** (`PermissionCatalogService`, including custom `@smrt` actions — not just CRUD)\nand enforces it two ways: app-side via `assertOperationPermission()` / `PermissionResolver`,\nand at the database via generated **Postgres RLS** policies\n(`generatePostgresPermissionSql()` / `applyPostgresPermissionPolicies()`) that read the\nsession-injected `smrt.permissions` / `smrt.tenant_id` (set by `withSessionPermissionContext`\nvia `set_config`). Because the RLS teeth are at the data layer, enforcement is door-agnostic\n— REST, MCP, and in-process callers are all bounded once the principal's context is set.\nSetup: README → *Manifest-derived permission catalog* and *Postgres RLS enforcement*.\n\n- Use `assertOperationPermission()` for hand-written mutations in SvelteKit form\n actions, custom endpoints, CLI scripts, and jobs. It derives the same\n `<collection>.<action>` slugs as `PermissionCatalogService` (`list`/`get` →\n `read`), requires the slug to exist in the catalog, then resolves permissions\n through `PermissionResolver`.\n- `assertOperationPermission()` throws fail-closed by default. Use\n `{ onDeny: 'return' }`, `checkOperationPermission()`, or\n `hasOperationPermission()` when a structured/boolean result is needed.\n- **Resource-tenant calling convention**: for resource-anchored authorization,\n pass the **resource's** tenant id — `tenantId: resourceTenantId` — not the\n session's current tenant. With `Role.inheritsToDescendants` flagged, a\n root-tenant admin then passes for any descendant resource with no app-side\n authority logic (and no membership fan-out), while per-child delegation and\n DENY precedence keep working. Do NOT pass a session-scoped `membership`\n alongside a different resource `tenantId` — a membership/tenant mismatch\n fails closed by design; omit `membership` and let the resolver look it up.\n- System context and super-admin bypass context are honored for parity with\n Postgres RLS. Pass `{ allowSuperAdminBypass: false }` on money-class or\n separation-of-duties operations that must require an explicit permission grant.\n- **Postgres RLS and membership inheritance**: RLS policies check the\n session-injected `smrt.permissions` list (resolved app-side by\n `PermissionResolver`), so a session whose `smrt.tenant_id` IS the child\n tenant gets inherited authority in RLS automatically. But RLS row filtering\n stays bound to the session's tenant setting — a root-tenant session acting\n on child-tenant rows is authorized by the app-level guard (resource-tenant\n convention above), not by RLS. This is a documented divergence, mirroring\n how #1829 handled bypass parity.\n- Seed role mappings with `RolePermissionCollection.seedRolePermissions()` or\n `RoleCollection.seedSystemRoles({ seedPermissions: true })`. The default\n matrix maps owner/admin to all catalog permissions, member to read/create for\n ordinary app resources, and viewer to read-only. Member create grants\n intentionally exclude users/RBAC authority and security resources (`users`,\n `tenants`, `roles`, `permissions`, memberships, groups, sessions, magic-link\n tokens, and related join/override tables). Re-seeding is additive and\n idempotent; pruning stale mappings requires `{ prune: true }`. When a\n contributing package registers a new built-in self-personalization\n permission after system roles already exist, call the explicit,\n idempotent `RolePermissionCollection.seedDefaultRolePersonalizationPermissions()`\n upgrade helper; it targets owner/admin/member/viewer only and never grants\n custom roles.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n- Two independent downward flows: the `TenantPermissionOverride` **cascade**\n (tenant-level permission config, flags above) and **membership-role\n inheritance** (`Role.inheritsToDescendants`, per-role opt-in — see\n \"Membership selection\" above). The cascade flags do not gate membership\n inheritance.\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Mobile `/api/mobile` Handlers (ADR 0001 Phase 3.5, #1748)\n\n`createMobileAuthHandlers(options)` (from `/sveltekit`) returns the mountable\nserver side of the KMP mobile contract: `authStart` (`POST auth/start`,\nserver-brokered PKCE via `OidcLoginService`), `authComplete`\n(`POST auth/complete`, code + echoed `state`/`codeVerifier` → bearer\nsession), `session.GET`/`session.DELETE` (bootstrap/logout), and\n`guard`/`withSession` — the bearer middleware for app-owned mobile routes.\nCore logic lives in `MobileAuthService` (framework-agnostic; exported from\nthe package root).\n\n- **Bearer = session id** (same convention as `TerminalAuthService`); 401\n bodies are `{ error, code }` and drive the mobile client's re-auth flow.\n- **Stateless handshake**: the OAuth `state` is an HMAC-signed token\n (secret: `stateSecret` ?? provider `clientSecret`) carrying\n nonce/provider/createdAt — full ID-token nonce verification with no\n server-side pending state. The `codeVerifier` never enters a URL: it is\n client-held per the frozen contract.\n- **Wire DTOs** come from `@happyvertical/smrt-mobile-contract`\n (`MobileAuthStartRequest` etc.) — one owning package for the Kotlin,\n Swift, and TypeScript shapes (compile-checked descriptors + parity test).\n- **Tenant options** honor `Role.inheritsToDescendants` (#1867): direct\n ACTIVE memberships plus descendants of flagged memberships (nearest\n flagged ancestor labels the option; any direct row pins; inactive direct\n rows exclude). Session binding defaults to the first DIRECT tenant —\n override with `resolveTenantId`.\n- **Hooks**: `resolveUser` (invite-gating; default provisions via\n `getOrCreateFromOidc`), `resolveTenantId`, `buildExtras` (bootstrap\n `extras`; model JSON must use `toPublicJSON({ permissions })` — #1822).\n `buildExtras` is the only app-domain bootstrap extension point. Never emit\n app fields such as `dashboard` at the response top level: they are outside\n `MobileSessionBootstrap` and the Kotlin decoder ignores them.\n- **Guard** wraps `withSessionPermissionContext`, so\n `assertOperationPermission`, tenancy context, and Postgres RLS all see the\n bearer caller; `OperationPermissionError` maps to 403 with a\n machine-readable `reason`.\n- **Uploads**: `resolveMobileUploadDedupKey` + the documented contract in\n `docs/content/architecture/mobile-upload-contract.md` (`clientCaptureId`\n field, `Idempotency-Key` header fallback); domain ingestion stays\n app-side. Framework-model writes ride `sync/apply`, not this path.\n- Configure `redirectUris` in production — RFC 8252 scheme rules always\n apply, but the allow list is the defense against redirecting authorization\n responses to attacker-controlled URIs.\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n- **RFC 9207 response issuer is exact.** OIDC callbacks validate a supplied\n `iss` against discovered metadata with exact string comparison before trusting\n a code or error. If metadata advertises issuer-response support, `iss` is\n required.\n- **Verified-email Profile reuse is fail-closed.** The typed canonical scenarios\n live in\n `packages/profiles/src/testing/oidcProvisioningDecisionMatrix.ts`; both\n package suites execute that matrix and public docs reference it rather than\n maintaining another behavioral table. Default provisioning reuses only one\n unowned, global `Person`. Tenant-scoped, non-Person, duplicate-email,\n and already-owned matches fail before User/session creation. An existing\n issuer/subject link without a User must still be the unique global Person for\n the current verified claim email; once owned, the stable issuer/subject link\n reuses its canonical Person and owner.\n Issuer and subject are opaque, case-sensitive identifiers; preserve their\n exact value and use trim only to reject blank claims.\n- **`resolveProfile` is the application reconciliation boundary.** The\n SvelteKit handlers, `OidcLoginService`, and `getOrCreateFromOidc` accept the\n same hook inside the provisioning transaction. The service/handler path\n supplies protocol-validated claims; direct collection callers must validate\n and trust their claim source before calling `getOrCreateFromOidc`.\n Token/userinfo merging keeps `email` and `email_verified` paired to the same\n claim source; verification is never borrowed across sources.\n Resolver reads/writes use the supplied `db`, and the hook must be idempotent\n because a concurrent unique-key conflict can retry it. `undefined` chooses\n the secure default and `null` rejects, including exact issuer/subject reuse.\n For a new identity, a supplied Profile is still validated as the unique,\n unowned global Person for the verified email. For an exact existing identity,\n it must be the already-linked Profile and cannot rebind identity authority;\n stable-link owner and canonical-Person checks still apply. The hook receives a\n separate frozen claims snapshot; internal retry and persistence state is not\n exposed for mutation.\n- **Owned first binding requires `authorizeProfileOwner`.** An invitation or\n approval workflow may explicitly return both its pre-provisioned canonical\n global `Person` and existing approved `User` from this transaction-bound\n hook. `undefined` keeps the secure `profile_owned` default and `null`\n rejects. SMRT treats only the selected IDs as input, reloads them in the\n provisioning transaction, and requires `email_verified === true`, the unique\n canonical global Person for the normalized claim email, exactly one owner,\n that owner as the selected User, and the same normalized User email. The\n hook runs before identity/User/session creation and may be retried, so use\n only its supplied `db` and `users` handles and keep application authorization\n idempotent. Never authorize from email matching alone. Existing exact\n identities cannot be rebound; when `resolveProfile` is also present both\n hooks must select the same Profile.\n- **OIDC first login is atomic.** The Profile, `OidcIdentity`, and User are one\n transaction. The database arbiters are `OidcIdentity.identityKey`,\n private `oidc_profile_email_reservations.email_key`, `User.emailKey`, and the\n unique `User.profileId`; local callbacks acquire exact issuer/subject and normalized\n email locks in deterministic order so changed email claims also serialize.\n SQLite and DuckDB callbacks additionally serialize every root-handle statement\n the coordinator owns per database URL — `_smrt_backfills` initialization, the\n transaction, and the post-commit rebind — because one adapter multiplexes a\n single native connection and cannot safely overlap unrelated root\n transactions. Never overlap two statements on one such handle, inside a\n transaction or not: rebind and owner/email candidate reads are sequential,\n never `Promise.all`. Owner-authorized DuckDB callbacks use that same\n root-handle serialization;\n PostgreSQL deadlock and serialization errors use a bounded transaction retry.\n Newly provisioned Profiles use non-semantic per-profile slugs so equal IdP\n display names cannot trigger a natural-key upsert;\n run\n `smrt db:status`, `smrt db:migrate`, then `smrt db:status` before deployment.\n Stop or upgrade old writers first. Before migration, group\n non-null `users.profile_id` values, then reconcile duplicates. After\n migration, run public `backfillProfileEmailKeys(db)` followed by\n `backfillUserEmailKeys(db)` from one deploy process. Both use the shared\n TypeScript `normalizeIdentityEmail()` implementation transactionally and are\n idempotent; the User backfill fails before writes if normalized duplicates\n remain. Every OIDC path requires the Profile email-key readiness marker;\n creating a User or checking User email uniqueness additionally requires the\n User marker. A stable issuer/subject with an existing owning User skips only\n the User email-key lookup and marker. Full scans remain in the explicit deploy\n step; guarded runtime paths use indexed keys and validate only returned\n candidates. Multiple null links remain valid.\n Legacy race keys backfill only after canonical validation. Pass a root\n database on adapters such as DuckDB that cannot create nested savepoints.\n Root adapters must expose `beginTransaction`; transaction-only handles are\n ambiguous and fail closed before provisioning writes. Caller-owned\n transactions never run `_smrt_backfills` DDL and require that table to\n already exist; use the root database when initialization or recovery is\n needed.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n",
|
|
4667
4797
|
"moduleDocs": [
|
|
4668
4798
|
{
|
|
4669
4799
|
"path": "agents/retention.md",
|
|
4670
4800
|
"module": "retention",
|
|
4671
|
-
"content": "# smrt-users/credential retention\n\nModule semantics for `src/retention.ts` and the three `deleteExpired()` paths\nit drives. Package orientation, the permission model, and the security rules\nthat apply before editing anything live in [../AGENTS.md](../AGENTS.md) — read\nthat first.\n\n## Credential retention (#2375)\n\n`SessionCollection.deleteExpired()`,\n`UsersMagicLinkTokenCollection.deleteExpired()` and\n`UsersCliAuthRequestCollection.deleteExpired()` all existed, and all waited for\nan application to remember to call them. Expired credential rows are the worst\nkind of unbounded growth: worthless the moment they expire, and exactly the\nrows an attacker would like to still find in the table.\n\n`src/retention.ts` contributes the three to the framework retention sweep in\n`@happyvertical/smrt-core`, so `smrt db:prune` and a running jobs `TaskRunner`\nreap them.\n\n- **The entry point registers on import.** `src/index.ts` calls\n `registerUserRetentionTasks()`, so any process that loaded this package\n contributes the tasks — including `smrt db:prune`, which imports the package\n optionally for exactly that reason. Registering is not scheduling: nothing is\n deleted until something runs a sweep.\n- **Task names** are `users-sessions`, `users-magic-link-tokens`,\n `users-cli-auth-requests` — prefixed with the package's short name because\n the retention registry is one process-global namespace. Opt one out with\n `runRetentionSweep(db, { tasks: { 'users-sessions': false } })` or\n `smrt db:prune --skip users-sessions`; `unregisterUserRetentionTasks()`\n removes all three.\n- **There is no retention window to configure.** An expired credential has\n nothing worth retaining, so each task deletes only already-expired rows. An\n application that keeps expired sessions for audit should opt the task out and\n archive them itself.\n- **All three are a single counted DELETE**, not a hydrate-and-delete loop.\n They now run unattended on a timer, and a per-row delete that throws part-way\n leaves the rest of the expired rows un-reaped — the #1400 reasoning that\n already applied to sessions, now applied to the other two. Counting first\n also gives a usable figure where `rowCount` is not populated, and is what\n makes `{ dryRun }` preview the same predicate rather than an estimate. The\n count and the delete are not one transaction, so the figure is approximate\n under concurrent writers.\n- **`expiresAt` is `@field({ indexed: true })`** on `Session`,\n `UsersMagicLinkToken` and `UsersCliAuthRequest`: the prune predicate scans\n that column on every pass.\n"
|
|
4801
|
+
"content": "# smrt-users/credential retention\n\nModule semantics for `src/retention.ts` and the three `deleteExpired()` paths\nit drives. Package orientation, the permission model, and the security rules\nthat apply before editing anything live in [../AGENTS.md](../AGENTS.md) — read\nthat first.\n\n## Credential retention (#2375)\n\n`SessionCollection.deleteExpired()`,\n`UsersMagicLinkTokenCollection.deleteExpired()` and\n`UsersCliAuthRequestCollection.deleteExpired()` all existed, and all waited for\nan application to remember to call them. Expired credential rows are the worst\nkind of unbounded growth: worthless the moment they expire, and exactly the\nrows an attacker would like to still find in the table.\n\n`src/retention.ts` contributes the three to the framework retention sweep in\n`@happyvertical/smrt-core`, so `smrt db:prune` and a running jobs `TaskRunner`\nreap them.\n\n- **The entry point registers on import.** `src/index.ts` calls\n `registerUserRetentionTasks()`, so any process that loaded this package\n contributes the tasks — including `smrt db:prune`, which imports the package\n optionally for exactly that reason. Registering is not scheduling: nothing is\n deleted until something runs a sweep.\n- **Task names** are `users-sessions`, `users-magic-link-tokens`,\n `users-cli-auth-requests` — prefixed with the package's short name because\n the retention registry is one process-global namespace. Opt one out with\n `runRetentionSweep(db, { tasks: { 'users-sessions': false } })` or\n `smrt db:prune --skip users-sessions`; `unregisterUserRetentionTasks()`\n removes all three.\n- **There is no retention window to configure.** An expired credential has\n nothing worth retaining, so each task deletes only already-expired rows. An\n application that keeps expired sessions for audit should opt the task out and\n archive them itself.\n- **All three are a single counted DELETE**, not a hydrate-and-delete loop.\n They now run unattended on a timer, and a per-row delete that throws part-way\n leaves the rest of the expired rows un-reaped — the #1400 reasoning that\n already applied to sessions, now applied to the other two. Counting first\n also gives a usable figure where `rowCount` is not populated, and is what\n makes `{ dryRun }` preview the same predicate rather than an estimate. The\n count and the delete are not one transaction, so the figure is approximate\n under concurrent writers.\n- **`expiresAt` is `@field({ indexed: true })`** on `Session`,\n `UsersMagicLinkToken` and `UsersCliAuthRequest`: the prune predicate scans\n that column on every pass.\n- **CLI bearer handoff is single-use.** An approved request becomes `consumed`\n and clears its `sessionId` when one poller wins the exchange. The CLI\n retention task deletes pending requests past their TTL, requests already\n marked `expired` by lazy expiry, and consumed history; it retains approved\n requests until exchange so a near-expiry approval cannot orphan its bearer\n session.\n"
|
|
4672
4802
|
}
|
|
4673
4803
|
]
|
|
4674
4804
|
}
|
package/dist/sveltekit.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as decodeOidcTransaction, E as resolveOidcProviderConfig, S as OidcLoginService, T as getUsersOidcConfig, _ as readMobileBearerToken, a as TerminalAuthRateLimitError, g as MobileAuthService, h as MobileAuthError, i as TerminalAuthError, m as withSessionPermissionContext, o as TerminalAuthService, s as OperationPermissionError, v as validateMobileRedirectUri, w as encodeOidcTransaction, x as OidcLoginError, y as SessionService } from "./chunks/TerminalAuthService-
|
|
1
|
+
import { C as decodeOidcTransaction, E as resolveOidcProviderConfig, S as OidcLoginService, T as getUsersOidcConfig, _ as readMobileBearerToken, a as TerminalAuthRateLimitError, g as MobileAuthService, h as MobileAuthError, i as TerminalAuthError, m as withSessionPermissionContext, o as TerminalAuthService, s as OperationPermissionError, v as validateMobileRedirectUri, w as encodeOidcTransaction, x as OidcLoginError, y as SessionService } from "./chunks/TerminalAuthService-CAomvhMa.js";
|
|
2
2
|
import { DiscoveryArtifactValidationError, SMRT_APP_RESULT_CONTRACT, SMRT_APP_RESULT_SCHEMA, SMRT_APP_RESULT_VERSION, SMRT_DISCOVERY_CONFORMANCE_ARTIFACT_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_VERSION, SMRT_MCP_RESULT_METADATA_KEY, canonicalizeDiscoveryArtifact, createDiscoveryConformanceArtifact, deriveCommandRequirements, validateDiscoveryConformanceArtifact } from "./app-contract.js";
|
|
3
3
|
import { ObjectRegistry } from "@happyvertical/smrt-core";
|
|
4
4
|
import { createLogger } from "@happyvertical/logger";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-users",
|
|
3
|
-
"version": "0.42.
|
|
3
|
+
"version": "0.42.5",
|
|
4
4
|
"description": "Multi-tenant user management for the SMRT framework - users, tenants, roles, permissions, groups",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"smrtRawPrimitives": "strict",
|
|
@@ -48,13 +48,13 @@
|
|
|
48
48
|
"@happyvertical/logger": "^0.88.0",
|
|
49
49
|
"@happyvertical/sql": "^0.88.0",
|
|
50
50
|
"jose": "^6.2.3",
|
|
51
|
-
"@happyvertical/smrt-config": "0.42.
|
|
52
|
-
"@happyvertical/smrt-core": "0.42.
|
|
53
|
-
"@happyvertical/smrt-mobile-contract": "0.42.
|
|
54
|
-
"@happyvertical/smrt-profiles": "0.42.
|
|
55
|
-
"@happyvertical/smrt-tenancy": "0.42.
|
|
56
|
-
"@happyvertical/smrt-types": "0.42.
|
|
57
|
-
"@happyvertical/smrt-ui": "0.42.
|
|
51
|
+
"@happyvertical/smrt-config": "0.42.5",
|
|
52
|
+
"@happyvertical/smrt-core": "0.42.5",
|
|
53
|
+
"@happyvertical/smrt-mobile-contract": "0.42.5",
|
|
54
|
+
"@happyvertical/smrt-profiles": "0.42.5",
|
|
55
|
+
"@happyvertical/smrt-tenancy": "0.42.5",
|
|
56
|
+
"@happyvertical/smrt-types": "0.42.5",
|
|
57
|
+
"@happyvertical/smrt-ui": "0.42.5"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@sveltejs/package": "^2.5.8",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
"typescript": "5.9.3",
|
|
67
67
|
"vite": "8.1.4",
|
|
68
68
|
"vitest": "4.1.10",
|
|
69
|
-
"@happyvertical/smrt-vitest": "0.42.
|
|
69
|
+
"@happyvertical/smrt-vitest": "0.42.5"
|
|
70
70
|
},
|
|
71
71
|
"keywords": [
|
|
72
72
|
"smrt",
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
"clean": "rm -rf dist",
|
|
96
96
|
"dev": "npm run build:watch",
|
|
97
97
|
"test": "vitest run",
|
|
98
|
-
"test:postgres": "node ../../scripts/run-with-ci-postgres.mjs -- pnpm exec vitest run src/__tests__/permission-postgres-rls.test.ts src/__tests__/principal-permission-context-postgres.test.ts src/__tests__/oidc-provisioning-postgres.test.ts",
|
|
98
|
+
"test:postgres": "node ../../scripts/run-with-ci-postgres.mjs -- pnpm exec vitest run src/__tests__/permission-postgres-rls.test.ts src/__tests__/principal-permission-context-postgres.test.ts src/__tests__/oidc-provisioning-postgres.test.ts src/__tests__/terminal-auth-postgres.test.ts",
|
|
99
99
|
"typecheck": "tsc --noEmit && node ../../scripts/svelte-check-a11y.mjs --tsconfig ./tsconfig.svelte.json",
|
|
100
100
|
"check": "pnpm exec svelte-check --tsconfig ./tsconfig.svelte.json",
|
|
101
101
|
"verify:pack": "node ../../scripts/verify-package-types-exports.js ."
|