@happyvertical/smrt-users 0.57.21 → 0.57.23
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/AGENTS.md +101 -0
- package/README.md +53 -1
- package/dist/chunks/{PasswordCredentialService-DezdsV_v.js → PasswordCredentialService-DA2Y6H2X.js} +8 -2
- package/dist/chunks/PasswordCredentialService-DA2Y6H2X.js.map +1 -0
- package/dist/chunks/{TerminalAuthService-D7SIRyUk.js → TerminalAuthService-VRpBNnsC.js} +3 -3
- package/dist/chunks/TerminalAuthService-VRpBNnsC.js.map +1 -0
- package/dist/collections/MagicLinkTokenCollection.d.ts +2 -0
- package/dist/collections/MagicLinkTokenCollection.d.ts.map +1 -1
- package/dist/collections/UserCollection.d.ts +2 -0
- package/dist/collections/UserCollection.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +590 -64
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +34 -1
- package/dist/member-register/service.d.ts +18 -2
- package/dist/member-register/service.d.ts.map +1 -1
- package/dist/operator.js +1 -1
- package/dist/services/LoginAttemptLimiter.d.ts +2 -0
- package/dist/services/LoginAttemptLimiter.d.ts.map +1 -1
- package/dist/services/MagicLinkService.d.ts +11 -1
- package/dist/services/MagicLinkService.d.ts.map +1 -1
- package/dist/services/MailboxAuthenticationService.d.ts +61 -0
- package/dist/services/MailboxAuthenticationService.d.ts.map +1 -0
- package/dist/services/TenantInvitationService.d.ts +120 -0
- package/dist/services/TenantInvitationService.d.ts.map +1 -0
- package/dist/services/index.d.ts +2 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +38 -5
- package/dist/sveltekit.js +2 -2
- package/package.json +10 -10
- package/dist/chunks/PasswordCredentialService-DezdsV_v.js.map +0 -1
- package/dist/chunks/TerminalAuthService-D7SIRyUk.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -184,3 +184,104 @@ Start with the relevant test file via `test -- src/__tests__/<file>.test.ts`.
|
|
|
184
184
|
Run `test:postgres` for RLS, principal context, OIDC, or terminal-auth database
|
|
185
185
|
changes. `typecheck` includes Svelte accessibility checks; plain `tsc` is
|
|
186
186
|
insufficient. Follow root knowledge freshness checks before shipping.
|
|
187
|
+
|
|
188
|
+
## Pending invitations
|
|
189
|
+
|
|
190
|
+
`TenantInvitationService.create({ db: tx, transaction: 'caller' }).prepare({
|
|
191
|
+
tenantId, email, roleSlug })` is a trusted host integration seam. The caller
|
|
192
|
+
must authorize the destination tenant and system role, serialize its invitation
|
|
193
|
+
scope, and own the entire transaction. It prepares only pending User and
|
|
194
|
+
Membership records, with a canonical global Person and email reservation;
|
|
195
|
+
it never proves email ownership, activates access, sends email, or mints login
|
|
196
|
+
credentials. Existing canonical User/Profile links remain unchanged; unowned
|
|
197
|
+
same-email Profiles require explicit reconciliation. Pending retries reuse rows,
|
|
198
|
+
active memberships remain active with their existing role, and inactive or
|
|
199
|
+
conflicting memberships fail closed. Caller failures must roll back the whole
|
|
200
|
+
transaction; retry identity uniqueness conflicts only after rollback. Run the
|
|
201
|
+
profile/user email-key backfills before using this service.
|
|
202
|
+
|
|
203
|
+
`issue({ membershipId })` requires the host to authorize that exact destination
|
|
204
|
+
and returns a signed single-use `{ membershipId, token, expiresAt }`; secure
|
|
205
|
+
delivery is the host’s responsibility (no email is sent). Configure `secret` and
|
|
206
|
+
optional `tokenExpiry` (1–604800 seconds, default one day) at service creation.
|
|
207
|
+
`accept({ membershipId, token, sessionId, expectedUserId? })` consumes the tenant
|
|
208
|
+
grant only after validating an independently authenticated, active exact User's
|
|
209
|
+
stored first-class OIDC, magic-link, password or passkey session. Layered,
|
|
210
|
+
permission-ceiling, terminal and unknown sessions fail closed. It activates only
|
|
211
|
+
the Membership; reuse/switch that session through canonical session APIs.
|
|
212
|
+
Never mint global identity sessions from an operator-copyable invitation.
|
|
213
|
+
|
|
214
|
+
For a new pending User, wire `authorizeOidcOwner(context, { membershipId, token })`
|
|
215
|
+
only into the canonical protocol-verified OIDC `authorizeProfileOwner` callback.
|
|
216
|
+
It requires the exact caller transaction, strict `email_verified: true` and the
|
|
217
|
+
exact canonical invitee email, consumes the grant and activates pending User
|
|
218
|
+
and Membership atomically before returning `{ profile, user, tenantId, membershipId }`.
|
|
219
|
+
Arbitrary claims must never reach this trusted callback seam. The canonical
|
|
220
|
+
binder still verifies ownership and issuer/subject authority before commit.
|
|
221
|
+
The signed scope fixes user, profile, tenant, membership and role; expiration,
|
|
222
|
+
replay, changed bindings, inactive membership and suspended users fail closed.
|
|
223
|
+
Nonce consumption and activation roll back together. `TenantInvitationError`
|
|
224
|
+
is an expected 400/403 refusal;
|
|
225
|
+
`MagicLinkError` represents invalid, expired or replayed proof. Database failures
|
|
226
|
+
remain distinct. Treat tokens as secrets, prefer URL fragments and POST bodies,
|
|
227
|
+
and never log or persist a copy outside the canonical token ledger.
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
## Independent emailed mailbox authentication
|
|
231
|
+
|
|
232
|
+
`MailboxAuthenticationService.create({db:tx,transaction:'caller',secret,loginLimiter})`
|
|
233
|
+
requests and verifies returning-client login without creating identities/sessions.
|
|
234
|
+
`request({email,sourceKey,deliver})` returns only `{requested:true}` for known,
|
|
235
|
+
unknown, malformed, pending, inactive or unauthorized accounts. The trusted server
|
|
236
|
+
`deliver({email,token,expiresAt})` callback sends only to the eligible canonical
|
|
237
|
+
active User's email; never expose a proof in HTTP responses/operator UI/logs,
|
|
238
|
+
including development. Ten-minute one-use proofs bind immutable User/Profile ids.
|
|
239
|
+
`authenticate({token,expectedUserId?,sessionId?})` rechecks canonical identity and
|
|
240
|
+
active tenant membership before consuming proof; returns only verified
|
|
241
|
+
`{userId,profileId,tenantId}` for the host's canonical magic-link session mint.
|
|
242
|
+
Existing signed-in identity must match; supplied sessions cannot have a parent,
|
|
243
|
+
permission ceiling, terminal/PIN/unknown method, or inactive principal.
|
|
244
|
+
|
|
245
|
+
For pending invitation onboarding, `requestMailboxAuthentication({membershipId,
|
|
246
|
+
token:projectGrant,sourceKey,deliver})` inspects but never consumes the signed
|
|
247
|
+
project grant, then delivers a DIFFERENT mailbox proof to the fixed invitee.
|
|
248
|
+
Only `{expiresAt}` is returned. `authenticateMailbox({membershipId,
|
|
249
|
+
invitationToken:projectGrant,token:mailedProof,expectedUserId?,sessionId?})` claims
|
|
250
|
+
BOTH proof nonces and activates pending canonical User/exact Membership in the
|
|
251
|
+
same caller transaction. Mailbox proof issuer binds all invitation ids, role and
|
|
252
|
+
SHA256 of the exact grant. A copied operator-visible grant cannot authenticate
|
|
253
|
+
identity. Repeated email requests do not burn the grant; only the first completed
|
|
254
|
+
authentication can claim it. Existing active-session/OIDC paths remain supported.
|
|
255
|
+
|
|
256
|
+
All refusals/caller failures must roll back the whole caller transaction. Mail
|
|
257
|
+
transport must reject on failure. Delivery is an external effect before commit:
|
|
258
|
+
a successfully delivered but rolled-back proof is unusable; retry may send another
|
|
259
|
+
mail. No session/authentication is valid without committed proof claims. The host
|
|
260
|
+
must set a bounded transport timeout and never return transport payloads/secrets.
|
|
261
|
+
No generic outbox/provider is required; compose the existing SDK email transport.
|
|
262
|
+
|
|
263
|
+
Both mail request operations REQUIRE a root-executor canonical
|
|
264
|
+
`LoginAttemptLimiter` passed as `loginLimiter`; missing limiters fail before
|
|
265
|
+
nonce/budget writes or delivery. Completion-only operations may omit it. Supply
|
|
266
|
+
the limiter independently from the caller transaction so
|
|
267
|
+
caller rollbacks cannot release send budgets (SQLite single-connection fixtures
|
|
268
|
+
cannot prove that production-pool separation). `sourceKey` is a trusted server
|
|
269
|
+
client-address key, never request-controlled forwarded headers; limiter hashes
|
|
270
|
+
and peppers it, never stores raw addresses/email. Each request retains its budget
|
|
271
|
+
through window expiry via `retainOnSuccess`, regardless of account eligibility.
|
|
272
|
+
Handle `LoginRateLimitError` with the same generic request response plus retry
|
|
273
|
+
policy. Returning request has a 250ms response floor; delivery latency remains
|
|
274
|
+
transport-dependent, so do not claim constant timing. Malformed/expired/replayed
|
|
275
|
+
proofs raise `MagicLinkError`; invitation binding/status refusals also use
|
|
276
|
+
`TenantInvitationError`. Database/transport faults remain distinguishable server
|
|
277
|
+
failures. Never swallow an error and commit a partially consumed transaction.
|
|
278
|
+
|
|
279
|
+
`MagicLinkService.inspect()` validates signed live nonce without claiming it;
|
|
280
|
+
it is preparation, never authentication. `verify()` remains the atomic claim.
|
|
281
|
+
Optional generated signed `subject` binds immutable identity; legacy callers
|
|
282
|
+
without a subject retain their existing result shape.
|
|
283
|
+
|
|
284
|
+
Focused matrix: `mailbox-authentication.test.ts` runs in memory SQLite by default;
|
|
285
|
+
`TEST_DB_ADAPTER=postgres` plus an explicit isolated `DATABASE_URL` creates a unique
|
|
286
|
+
schema per scenario and also exercises concurrent invitation/login proof claims.
|
|
287
|
+
It is registered in `test:postgres`; no shared local service fallback is used.
|
package/README.md
CHANGED
|
@@ -1563,6 +1563,57 @@ exports. A policy that requires shares or dues evidence fails closed unless the
|
|
|
1563
1563
|
register has an explicitly authoritative reference for every required kind; the
|
|
1564
1564
|
snapshot names that missing evidence rather than inferring payment status.
|
|
1565
1565
|
|
|
1566
|
+
For GET-style capabilities, use the member-scoped read API instead:
|
|
1567
|
+
|
|
1568
|
+
```typescript
|
|
1569
|
+
const register = new MemberRegisterService(db, { tenantId });
|
|
1570
|
+
const decision = await register.eligibilityFor(
|
|
1571
|
+
{ userId: signedInUser.id }, // or { memberId: legalMemberId }
|
|
1572
|
+
'2026-06-01',
|
|
1573
|
+
{ memberClassKeys: ['worker'], requireAuthoritativeKinds: ['dues'] },
|
|
1574
|
+
);
|
|
1575
|
+
```
|
|
1576
|
+
|
|
1577
|
+
`eligibilityFor(identity, recordDate, policy)` performs only reads on the supplied
|
|
1578
|
+
executor. It opens no transaction, persists no snapshot and never lists the
|
|
1579
|
+
register. Its query count is independent of unrelated members; history and
|
|
1580
|
+
references are loaded only for the selected member. Exactly one nonempty selector
|
|
1581
|
+
is required. A user identity must resolve to exactly one member in this tenant;
|
|
1582
|
+
missing, foreign and ambiguous identities throw `MEMBER_REGISTER_NOT_FOUND`.
|
|
1583
|
+
Malformed dates/selectors/policy values throw `MEMBER_REGISTER_INVALID`; an active
|
|
1584
|
+
foreign tenant context throws `MEMBER_REGISTER_TENANT_MISMATCH`. Database failures
|
|
1585
|
+
propagate. Hosts map these failures to denied capabilities and must derive tenant
|
|
1586
|
+
and identity from an authorized session, never trust submitted identity fields.
|
|
1587
|
+
This is legal-register eligibility: host-level suspension/bans and operation
|
|
1588
|
+
permissions still require their own checks. Individual reads do not promise a
|
|
1589
|
+
transactionally stable multi-query snapshot; an accepted command re-evaluates on
|
|
1590
|
+
its own transaction.
|
|
1591
|
+
|
|
1592
|
+
Persist immutable evidence explicitly when accepting a command:
|
|
1593
|
+
|
|
1594
|
+
```typescript
|
|
1595
|
+
await register.withTransaction(async (bound, executor) => {
|
|
1596
|
+
const snapshot = await bound.captureEligibility(
|
|
1597
|
+
{ memberId: legalMemberId }, '2026-06-01', policy,
|
|
1598
|
+
);
|
|
1599
|
+
if (!snapshot.eligible) throw new Error('Participation denied');
|
|
1600
|
+
// Persist the accepted command with executor, referencing snapshot.id.
|
|
1601
|
+
// Throwing rolls back both command and evidence.
|
|
1602
|
+
});
|
|
1603
|
+
```
|
|
1604
|
+
|
|
1605
|
+
`withTransaction` supplies a bound service and the exact database executor used
|
|
1606
|
+
by its reads and writes; callbacks must use that executor for their command and
|
|
1607
|
+
must not retain either value after completion. Nested calls through the bound
|
|
1608
|
+
service reuse the transaction. `captureEligibility` re-evaluates authoritative
|
|
1609
|
+
records and creates one immutable `MemberEligibilitySnapshot`, including the
|
|
1610
|
+
policy inputs. Called alone, it opens its own transaction. It does not accept a
|
|
1611
|
+
caller-authored decision or grant host authorization. Each successful call is a
|
|
1612
|
+
new evidence event; hosts implement command idempotency in the same transaction,
|
|
1613
|
+
and skip capture for an already accepted command. A refused or failed transaction
|
|
1614
|
+
leaves no snapshot. The existing `asOf` remains the explicit whole-register
|
|
1615
|
+
snapshot/export operation and is unsuitable for ordinary capability GETs.
|
|
1616
|
+
|
|
1566
1617
|
An omitted `memberClassKeys` policy allows every class; an explicit empty list
|
|
1567
1618
|
allows none. `statuses` defaults to `['active']`, and an empty status list also
|
|
1568
1619
|
allows none. Snapshots preserve normalized class keys (`null` means unrestricted),
|
|
@@ -1579,7 +1630,8 @@ all of their writes together. History and references are append-only, and
|
|
|
1579
1630
|
snapshots reject updates and deletes. Same-day history corrections use persisted
|
|
1580
1631
|
sequence order. Eligibility uses effective history; `LegalMember.status` and
|
|
1581
1632
|
`leftOn` are display caches refreshed by `setStatus`, so scheduled changes may
|
|
1582
|
-
make those caches stale until another write. Use `
|
|
1633
|
+
make those caches stale until another write. Use `eligibilityFor` for read-only
|
|
1634
|
+
record-date decisions, or `captureEligibility` for accepted-command evidence.
|
|
1583
1635
|
|
|
1584
1636
|
Use `revokeReference(referenceId, { effectiveOn })` when previously authoritative
|
|
1585
1637
|
evidence is withdrawn. It appends a dated record targeting the original reference;
|
package/dist/chunks/{PasswordCredentialService-DezdsV_v.js → PasswordCredentialService-DA2Y6H2X.js}
RENAMED
|
@@ -3908,6 +3908,12 @@ var UserCollection = class UserCollection extends SmrtCollection {
|
|
|
3908
3908
|
});
|
|
3909
3909
|
return results.length > 0 ? results[0] : null;
|
|
3910
3910
|
}
|
|
3911
|
+
/** Indexed identity lookup with readiness and ambiguity guards. */
|
|
3912
|
+
async findCanonicalByEmail(email) {
|
|
3913
|
+
const matches = await this.findUsersByNormalizedEmail(normalizeIdentityEmail(email));
|
|
3914
|
+
if (matches.length > 1) throw new Error("Ambiguous User email identity");
|
|
3915
|
+
return matches[0] ?? null;
|
|
3916
|
+
}
|
|
3911
3917
|
/**
|
|
3912
3918
|
* Find user by profile ID
|
|
3913
3919
|
*/
|
|
@@ -4568,7 +4574,7 @@ var LoginAttemptLimiter = class LoginAttemptLimiter {
|
|
|
4568
4574
|
},
|
|
4569
4575
|
succeed: async (metadata) => {
|
|
4570
4576
|
settle();
|
|
4571
|
-
await this.releaseAll(reserved, true);
|
|
4577
|
+
if (!input.retainOnSuccess) await this.releaseAll(reserved, true);
|
|
4572
4578
|
await audit("succeeded", { metadata: {
|
|
4573
4579
|
...input.metadata,
|
|
4574
4580
|
...metadata
|
|
@@ -6126,4 +6132,4 @@ var PasswordCredentialService = class PasswordCredentialService {
|
|
|
6126
6132
|
//#endregion
|
|
6127
6133
|
export { PermissionCatalogService as $, InvalidCredentialsError as A, Session as At, backfillUserEmailKeys as B, DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS as C, SessionCollection as Ct, DEFAULT_LOGIN_MAX_ATTEMPTS as D, normalizeUsername as Dt, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS as E, normalizeEmail as Et, withoutListBounds as F, __exportAll as Ft, MAX_TENANT_HIERARCHY_DEPTH as G, TenantPermissionOverride as H, OidcProvisioningError as I, assertTenantTableName as J, TenantHierarchyError as K, UserCollection as L, LoginRateLimitError as M, Role as Mt, hashSecret as N, Permission as Nt, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS as O, DEFAULT_SESSION_TTL as Ot, verifySecretHash as P, Membership as Pt, RolePermissionCollection as Q, USER_EMAIL_KEY_BACKFILL_NAME as R, normalizeAncestorReadPolicy as S, UsersLoginAttempt as St, DEFAULT_LOGIN_LOCKOUT_FACTOR as T, isValidEmail as Tt, TenantCollection as U, TenantPermissionOverrideCollection as V, Tenant as W, recordTenantHierarchyChanges as X, planTenantHierarchy as Y, DEFAULT_ROLE_PERMISSION_PATTERNS as Z, PermissionResolver as _, GroupCollection as _t, DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS as a, RolePermission as at, getConfiguredAncestorReadPolicy as b, UsersLoginAuditEvent as bt, PASSWORD_PERMISSION_DEFINITIONS as c, UsersPasswordCredentialCollection as ct, PasswordCredentialForbiddenError as d, MembershipOverride as dt, deriveOperationPermissionCollectionName as et, PasswordCredentialService as f, MembershipCollection as ft, SessionService as g, GroupMember as gt, outOfBandProofSessionData as h, GroupMemberCollection as ht, DEFAULT_PASSWORD_MIN_LENGTH as i, syncPermissionCatalog as it, LoginAttemptLimiter as j, generateSessionId as jt, DurableLoginAuditSink as k, SESSION_DATA_KEYS as kt, PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS as l, UsersPasswordCredential as lt, ensurePasswordPermissionsRegistered as m, GroupRole as mt, DEFAULT_PASSWORD_MANAGE_PERMISSION as n, normalizeOperationPermissionAction as nt, PASSWORD_LOGIN_KIND as o, RoleCollection as ot, PasswordPolicyError as p, GroupRoleCollection as pt, applyTenantHierarchyUpdates as q, DEFAULT_PASSWORD_MAX_LENGTH as r, registerPermissionDefinitions as rt, PASSWORD_MAX_LENGTH_CEILING as s, PermissionCollection as st, DEFAULT_PASSWORD_DENYLIST as t, deriveOperationPermissionSlug as tt, PasswordCredentialError as u, MembershipOverrideCollection as ut, ANCESTOR_READ_ACTION as v, Group as vt, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS as w, User as wt, isAncestorReadableSlug as x, UsersLoginAttemptCollection as xt, DEFAULT_ANCESTOR_READ_MAX_DEPTH as y, UsersLoginAuditEventCollection as yt, UserEmailKeyBackfillError as z };
|
|
6128
6134
|
|
|
6129
|
-
//# sourceMappingURL=PasswordCredentialService-
|
|
6135
|
+
//# sourceMappingURL=PasswordCredentialService-DA2Y6H2X.js.map
|