@happyvertical/smrt-users 0.57.20 → 0.57.22

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 (30) hide show
  1. package/AGENTS.md +101 -0
  2. package/dist/chunks/{PasswordCredentialService-DezdsV_v.js → PasswordCredentialService-DA2Y6H2X.js} +8 -2
  3. package/dist/chunks/PasswordCredentialService-DA2Y6H2X.js.map +1 -0
  4. package/dist/chunks/{TerminalAuthService-_IB-tAgS.js → TerminalAuthService-pHNqf5o3.js} +3 -3
  5. package/dist/chunks/TerminalAuthService-pHNqf5o3.js.map +1 -0
  6. package/dist/collections/MagicLinkTokenCollection.d.ts +2 -0
  7. package/dist/collections/MagicLinkTokenCollection.d.ts.map +1 -1
  8. package/dist/collections/UserCollection.d.ts +2 -0
  9. package/dist/collections/UserCollection.d.ts.map +1 -1
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +477 -14
  13. package/dist/index.js.map +1 -1
  14. package/dist/manifest.json +34 -1
  15. package/dist/operator.js +1 -1
  16. package/dist/services/LoginAttemptLimiter.d.ts +2 -0
  17. package/dist/services/LoginAttemptLimiter.d.ts.map +1 -1
  18. package/dist/services/MagicLinkService.d.ts +11 -1
  19. package/dist/services/MagicLinkService.d.ts.map +1 -1
  20. package/dist/services/MailboxAuthenticationService.d.ts +61 -0
  21. package/dist/services/MailboxAuthenticationService.d.ts.map +1 -0
  22. package/dist/services/TenantInvitationService.d.ts +120 -0
  23. package/dist/services/TenantInvitationService.d.ts.map +1 -0
  24. package/dist/services/index.d.ts +2 -0
  25. package/dist/services/index.d.ts.map +1 -1
  26. package/dist/smrt-knowledge.json +38 -5
  27. package/dist/sveltekit.js +2 -2
  28. package/package.json +10 -10
  29. package/dist/chunks/PasswordCredentialService-DezdsV_v.js.map +0 -1
  30. package/dist/chunks/TerminalAuthService-_IB-tAgS.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.
@@ -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-DezdsV_v.js.map
6135
+ //# sourceMappingURL=PasswordCredentialService-DA2Y6H2X.js.map