@voltro/plugin-auth 0.6.0 → 0.7.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.
package/CHANGELOG.md CHANGED
@@ -39,6 +39,26 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.7.0] — 2026-07-20
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/runtime** — Row-level security: a `load` failure is now retried, and then surfaces as an **error** instead of an empty result. `setRowFilter({ load, predicate })` resolves `load` once per request; previously ANY failure was answered with a predicate matching zero rows. A downstream app reported the consequence correctly — for shared/team visibility `load` must read the store, so one transient DB blip denied every constrained table for that request and the whole UI rendered empty. Two distinct defects, fixed separately, because conflating them was the original mistake. **A transient failure should never reach the decision:** `load` had no retry at all, so a reaped connection was answered as if it were an authorization fact. It now runs under a bounded `retry` schedule — `DEFAULT_ROW_FILTER_RETRY`, three attempts backing off exponentially from 20ms, so ~60ms worst case — configurable per filter with your own `Schedule`, or `retry: false` for one attempt. **And refusal was expressed as an empty result, which is a lie:** "we could not determine your visibility" and "you may see nothing" are different facts, and only one of them is a fact. An empty list is byte-identical to legitimate emptiness, so the user reads "you have no tickets", the operator reads a healthy 200, and the outage is invisible to both — the most misleading outcome available. The module header used to defend this ("an empty result rather than a 500 on every page"); every constrained page IS broken, and saying so is the correct behavior. `onLoadError` now defaults to `'fail'`, raising the exported typed `RowFilterUnavailable`; `onLoadError: 'deny'` keeps the old degradation for apps that have looked at the screen and genuinely prefer an empty list to an error state, with the `onError` reporter still firing so the choice is not silent. The app asked for `onLoadError: 'fallthrough'` — fail OPEN to the handler's own check. Deliberately not implemented, and not planned. Serving unfiltered rows when the authorization filter is unavailable leaks data precisely when the system is under stress and nobody is reading dashboards, and it is only safe if every handler still carries the check that row filters exist to replace. Fail-closed is retained under both policies; a test asserts neither branch can ever yield an unfiltered read. **Migration.** `resolveRowFilterScope` gains an error channel — `Effect<RowFilterScope, RowFilterUnavailable>` instead of an infallible Effect — so direct callers (a custom entrypoint, a test harness) must handle it; TypeScript points at each one. Apps that want the previous behavior add `onLoadError: 'deny'`, but should decide that rather than default into it. Tests asserting "a broken load yields an empty result" now fail with `RowFilterUnavailable`, which is the fix working. Subscriptions changed shape too: a re-resolve that fails mid-delivery now REVOKES the subscription and emits a typed error frame — following the existing withdrawn-guard precedent — because an empty snapshot on a live subscription reads to a client as "every row you could see was just deleted". The same failure at subscribe time aborts the subscribe instead of opening a stream on a fabricated snapshot, and unwinds the matcher + dependent-table registration it had already made (previously leaked on any subscribe-time throw).
47
+ - **@voltro/testing, @voltro/runtime** — `@voltro/testing` now mirrors the runtime store's POLICY path, not only its DATA path. An adopting app found three places where the harness diverged, each of which made a class of rule untestable in-repo while leaving the suite green. **`invoke` runs Effect-mode handlers.** The framework's contract is "async OR Effect, your choice per handler", and every production runner honours it (`Effect.isEffect(result) ? … : …`). `invoke` only awaited the executor's return value, so an Effect-mode handler handed back its own un-run `EffectPrimitive`: nothing executed, nothing was written, and a test asserting on the "result" asserted on a description of work. The Effect now runs through `runProvidedEffect` — the same function the serve entrypoints use — so a handler failing with a typed error REJECTS WITH THAT ERROR rather than an opaque FiberFailure, and `EffectStore` + `SubjectService` are provided over the context the handler is actually given. Guards, the input decode, the transactional wrap, the deadlock replay, `afterCommit` and the plugin interceptor chain apply identically to both modes. **`makeTestContext({ relations: [spec] })`** registers `relations()` specs. `relations()` is pure — it returns a spec, it does not register one — and production registration is a boot step (`voltro dev` → `registerDiscoveredRelations`), so under the harness an eager load failed with "no relations registered" no matter what the test imported. The option REPLACES the process-global registry with exactly the specs given (the registry is a `Symbol.for` global; additive registration would throw `duplicate relation` on the second `makeTestContext` in a file and leak the first test's relations into the second). Omitting it touches the registry not at all. **The harness store applies row-level security.** After `setRowFilter(...)` a `makeTestContext` read of a constrained table returned the unfiltered set, so "user A cannot see user B's row" could not be asserted at all. `ctx.store` now resolves the filter for its subject and AND-merges it into every read — fluent builders and descriptor reads alike, not bypassed by `.unscoped()`, bypassed for a `system` subject. A new `rowFilter:` option passes a filter directly for tests that would rather not write to a process global. Resolution goes through the runtime's new `resolveRowFilterScopeFor` (`resolveRowFilterScope` is now that function applied to the registered filter), so the retry schedule, the system bypass and the `onLoadError` policy are the runtime's single definition rather than a second copy in the harness. **Breaking, and how to migrate** (`voltro update` prints this): delete any `Effect.isEffect(out) ? await Effect.runPromise(out) : out` shim around an `invoke` call — it is dead code that also destroyed your typed errors. `ProcedureExecutor<Input, Output>` gained an `Effect<Output, E>` arm and an optional third parameter `E` (default `never`); `invoke` now infers from the executor's whole return type instead of taking `Output` as its second type parameter, so an explicit `invoke<typeof d, Note>(…)` type-argument list must be dropped in favour of inference. Handlers themselves keep compiling — what changes is the type of a CALL.
48
+
49
+ ### Added
50
+
51
+ - **@voltro/plugin-auth** — `subjectFromUser(user, { metadata })` now carries arbitrary app metadata onto the Subject. Previously the helper set the metadata slot ONLY when `memberships` were supplied, so an app whose Subject must carry a provider credential — an Atlassian PAT captured at login and read back as `subject.metadata.jiraToken` by `@voltro/plugin-atlassian`'s `credentialsResolver`, say — could not adopt the helper at all: calling it silently dropped the credential, and building the Subject by hand was the only way to keep it. The framework shipped both halves of that gap itself. `metadata` MERGES with the memberships projection rather than replacing it. **Precedence when a `memberships` key appears in both:** the dedicated `memberships` option wins — it is the specific, typed input, and it is the one projected into the `{ tenantId, role }` shape `subjectMemberships()` and the switch-tenant menu read, so letting a free-form bag shadow it would break tenant switching in a way nothing type-checks. Without the option, a `memberships` key inside `metadata` passes through unchanged. A Subject built with neither option still has NO `metadata` key (not an empty object). The later stamps compose unchanged: the sign-in / sign-up / magic-link / passkey handlers spread the existing slot before adding `sessionId`, and the password strategy does the same for `provider`, so keys set through this option survive every login path — unless a caller names a key `sessionId` or `provider`, which those merges overwrite by design. **`handleSwitchTenant` now carries that metadata across a switch**, via a new optional `metadata` on `SwitchTenantInput` (the built-in `/switch-tenant` route passes the caller's `subject.metadata` for you). Without this the option above would have been a trap rather than a feature: a switch rebuilds the Subject from the user record, so an app parking a provider credential in the slot would lose it the first time a user changed tenant — staying authenticated while every call to the provider began failing, with no signal at the point that caused it. `memberships` is deliberately NOT carried: it is re-derived for the target tenant, and a carried copy would report a role the user does not hold there. Covered by a test that fails on the exact assertion when the carry is removed. `SwitchTenantInput` is now exported too — every sibling handler input (`SignInInput`, `MfaVerifyInput`, …) already was, and this one had simply been forgotten, so an app calling `handleSwitchTenant` directly could not name its argument type. Additive: the option is optional and callers that pass neither get byte-identical Subjects. `packages/plugin-auth/etc/plugin-auth.api.md` gains one line and changes none.
52
+ - **@voltro/database** — `timestampMs` and `timestampMsOrNull` — the timestamp wire mapping as STANDALONE field schemas, for hand-written `Schema.Struct` outputs. `Date` in the handler, epoch-ms `number` on the wire; `timestampMsOrNull` is the `.nullable()` column's variant, so a "never archived" row stays `null` instead of becoming `new Date(null)` (1970-01-01, which renders as a plausible date rather than as nothing). ```ts output: Schema.Struct({ id: Schema.String, addedAt: timestampMs, // Date in the handler, epoch ms on the wire archivedAt: timestampMsOrNull, seenAt: Schema.optional(timestampMs), }) ``` This closes the half of the problem `rowSchema(table)` left open. `rowSchema` only helps a handler returning a RAW FULL TABLE ROW, and real handlers overwhelmingly return a COMPUTED struct assembled across several tables — `{ id, name, slug, addedAt, jiraProjectKey }` — where there is no single table to derive from. That is exactly where the hand-written `Date → epoch` converters accumulate: the app that reported the original gap has ~228 of them, all in shaped outputs, and found zero clean applications for whole-row `rowSchema`. Single-sourced, not a parallel declaration: `columnSchema` now READS `timestampMs` for `timestamp()` / `date()` columns, so the derived-row and hand-written-struct paths are the same schema by identity and cannot drift into different wire representations. `rowSchema.test.ts` asserts that identity rather than asserting both merely produce a number. There is deliberately no `timestampMsOptional` — an absent field is `Schema.optional(timestampMs)`, which composes without a third export. Both exports live in the browser-safe `@voltro/database` main entry (pure `effect/Schema`, no driver, no `node:*`), which is what a descriptor's `output` needs. Additive: two new exports, no existing declaration changed. `packages/database/etc/database.api.md` gains two entries and changes none.
53
+
54
+ ### Fixed
55
+
56
+ - **@voltro/sql-turso** — Turso (local Rust engine): pooled connections now WAIT for a held lock instead of failing instantly with `database is locked`. The engine keeps SQLite's default of `PRAGMA busy_timeout = 0`, so any statement that met a lock held by another connection failed on the spot — and with the default pool of 4 connections on one file, two concurrent writers are enough to reach it. `makeConnection` now issues `busy_timeout` for every pooled connection, beside the mandatory MVCC and foreign-key pragmas. MVCC did not cover this and was the reason it was missed: `journal_mode=experimental_mvcc` resolves write-write conflicts BETWEEN transactions, while DDL and the schema lock stay exclusive, so the failure lands on statements the concurrency design appears to have handled. It also only reproduces under CPU contention — green on an idle machine, sporadic under load — which is the worst shape for a defect to have. It surfaced as a flaky `CREATE TABLE` in the MVCC keystone test during a full local gate run, where 78 packages build in parallel; a user would see it as an intermittent `database is locked` under production traffic with no obvious trigger. The default is 5000ms, matching better-sqlite3's own default — which is why the sibling `@voltro/sql-sqlite` never needed this: that driver sets the timeout for us, and the turso NAPI driver does not. Tunable via `busyTimeoutMs` on `makeTursoSqlLayer` / `TursoClientConfig`, beside `maxConnections`; `busyTimeoutMs: 0` explicitly restores the fail-immediately behavior (asserted by a test, so the default can never be implemented as a floor that silently ignores 0). It is deliberately NOT on the cross-dialect `ConnectionConfig` — that shape stays free of engine-specific knobs, the same reason the Turso auth token is env-sourced rather than threaded through it.
57
+ - **@voltro/cli** — `voltro update` now honors the project's actual package manager instead of defaulting to npm. It resolves the manager by walking from the app directory **up to the repo root**, preferring the corepack `packageManager` field over a lockfile (`pnpm-lock.yaml` / `yarn.lock` / `bun.lock` / `bun.lockb` / `package-lock.json`), and only falls back to npm when nothing declares one. Walking up fixes the workspace case: a scaffolded project keeps its lockfile at the monorepo root, so running `voltro update` from `apps/api` previously found no lockfile and ran `npm install` against a pnpm/yarn workspace — writing a stray lockfile and a nested `node_modules`. The resolved manager is also used for the latest-version registry lookup (`pnpm view` / `yarn` / `bun pm view`, with `npm view` as a last-resort fallback), so a private or scoped registry configured in `.npmrc` / `.yarnrc.yml` is honored. The yarn query dispatches on the installed yarn MAJOR version rather than probing berry syntax first: on yarn classic, `yarn npm info …` parses as `yarn run npm` and **executes a `npm` script from the project's package.json** if one exists — verified against yarn 1.22.22. Resolving a version number must never run user code, so classic gets `yarn info … --silent` and only berry (>=2) gets `yarn npm info`. All three managers are verified against real binaries in throwaway Docker containers — yarn classic 1.22.22, yarn berry 4.6.0, bun 1.3.14 — each asserting both that the query resolves a version and that it does not execute a same-named script. Re-run with `node scripts/smoke-package-managers.mjs`.
58
+ - **@voltro/cli** — Three fixes to `voltro update`, all reported by an app upgrading a pnpm workspace. **The bump is now LOCKSTEP across the whole workspace.** `voltro update` in `apps/api` bumped only that `package.json`, leaving the sibling web app and shared `packages/*` on the previous version — an api on 0.6.0 and a web client on 0.5.0 disagree about the generated rpcGroup types and the session cookie shape, and that disagreement surfaces as a runtime decode error, not a build error. When the app sits inside a workspace (`pnpm-workspace.yaml`, or a `workspaces` field in an ancestor `package.json`, found by the same bounded upward walk that resolves the package manager and stops at the first `.git`), every member `package.json` that declares `@voltro/*` is bumped to the target together, and the install runs **once at the workspace root** — running it inside `apps/api` corrupts a pnpm/yarn workspace's layout. Each file that will be bumped is listed in the plan output and in `--dry-run`. A standalone (non-workspace) project is unchanged: its own `package.json`, its own install, in place. The codemod re-exec now also looks for the installed `voltro` bin at the workspace root, since npm and yarn hoist it there. **A failed install now says that the codemods were skipped.** It previously printed only "install failed — package.json was bumped; fix the install and re-run", never mentioning codemods, so a user could boot on target-version code with source shaped for the old one and no signal as to why. The codemods for a jump ship *inside* the target version, which a failed install did not put on disk, so running them is impossible rather than merely undesirable — the fix is the message. It now states plainly that no codemods were applied, why, and prints the exact copy-pasteable recovery command with the concrete versions: `voltro update --codemods-only --from <from> --to <to>`. **`--help` / `-h` is answered before every guard.** `voltro update --help` on a dirty tree printed "working tree is not clean" — at precisely the moment the user was trying to discover `--dry-run` and `--codemods-only`. Help is documentation, not an operation, so it is now handled first, ahead of the `package.json` check, the `@voltro/*`-deps check and the clean-tree guard, and lists every flag (`--to`, `--from`, `--root`, `--dry-run`, `--force`, `--exact`, `--codemods-only`). `voltro doctor --help` had the same shape — it fell through to the preflight and reported on the tree instead — and gets the same treatment. `voltro help`'s `update` line now names `--from` and `--codemods-only` too.
59
+
60
+ ---
61
+
42
62
  ## [0.6.0] — 2026-07-19
43
63
 
44
64
  ### ⚠ BREAKING
package/dist/index.d.ts CHANGED
@@ -855,10 +855,32 @@ export declare interface SignUpInput {
855
855
  * framework never reads it, but app code + the switch-tenant menu do).
856
856
  * Pass an explicit `tenantId` to make the ACTIVE tenant differ from the
857
857
  * user's home tenant (post switch-tenant rebind).
858
+ *
859
+ * `metadata` carries anything else the app needs on the Subject — most
860
+ * often a provider credential captured at login and read back by a
861
+ * plugin's `credentialsResolver` (`subject.metadata.jiraToken` for
862
+ * `@voltro/plugin-atlassian`, say). Without it an app that needs such a
863
+ * credential could not adopt this helper at all: building the Subject by
864
+ * hand was the only way to keep the value.
865
+ *
866
+ * **Precedence, when a `memberships` key appears in BOTH:** the dedicated
867
+ * `memberships` option wins. It is the specific, typed input and it is
868
+ * projected to the `{ tenantId, role }` shape `subjectMemberships` reads,
869
+ * so letting a free-form bag silently shadow it would break the
870
+ * switch-tenant menu in a way nothing type-checks. A `memberships` key
871
+ * inside `metadata` is passed through UNCHANGED when the option is absent
872
+ * — no reshaping, no validation.
873
+ *
874
+ * Note this only stamps the metadata slot at CONSTRUCTION. The sign-in /
875
+ * sign-up / magic-link / passkey handlers later merge `sessionId` (and
876
+ * the password strategy merges `provider`) onto whatever is here, so keys
877
+ * set through this option survive those paths — unless you name a key
878
+ * `sessionId` or `provider`, which those merges overwrite by design.
858
879
  */
859
880
  export declare const subjectFromUser: (user: UserRecord, options?: {
860
881
  readonly tenantId?: string;
861
882
  readonly memberships?: ReadonlyArray<MembershipRecord>;
883
+ readonly metadata?: Record<string, unknown>;
862
884
  }) => Subject;
863
885
 
864
886
  /**
@@ -886,7 +908,7 @@ export declare const subjectMemberships: (subject: Subject) => ReadonlyArray<{
886
908
  role: string;
887
909
  }>;
888
910
 
889
- declare interface SwitchTenantInput {
911
+ export declare interface SwitchTenantInput {
890
912
  readonly userId: string;
891
913
  /** The connection (clientId) whose subject to rebind, when invoked over
892
914
  * the live WS path. Absent on the pure HTTP path (cookie re-issue only). */
@@ -896,6 +918,20 @@ declare interface SwitchTenantInput {
896
918
  * re-issued cookie so the request-time revocation check keeps
897
919
  * covering the session after a tenant switch. */
898
920
  readonly sessionId?: string;
921
+ /**
922
+ * The metadata on the caller's CURRENT subject, carried onto the re-issued
923
+ * one. Pass `subject.metadata` — the route does.
924
+ *
925
+ * Load-bearing, not a convenience: a switch rebuilds the Subject from the
926
+ * user record, so anything an app put in the metadata slot is otherwise
927
+ * dropped the first time someone changes tenant. For an app that carries a
928
+ * provider credential there (an Atlassian PAT read back by
929
+ * `credentialsResolver`, say) that means the integration silently dies on
930
+ * switch — the user stays authenticated, and every call to the provider
931
+ * starts failing. `memberships` and `tenantId` are deliberately NOT carried:
932
+ * they are re-derived for the target tenant and stale copies would be wrong.
933
+ */
934
+ readonly metadata?: Record<string, unknown>;
899
935
  }
900
936
 
901
937
  export declare type TokenPurpose = 'magic-link' | 'password-reset' | 'mfa-pending';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { PasswordEmptyError as e, PasswordHashError as t, hashPassword as n, needsRehash as r, parseScryptParams as i, verifyPassword as a, verifyPasswordWithRehash as o } from "./password.js";
2
2
  import { SESSION_COOKIE_NAME as s, clearSessionCookie as ee, issueSession as te, readSession as c, readSessionKeyed as l, resolveSessionSecret as u, resolveSessionSecrets as d, sessionSecretsOf as f } from "./session.js";
3
- import { a as p, c as m, i as h, l as g, n as _, o as v, r as y, s as b, t as x } from "./strategy-CQ2YCIcr.js";
4
- import { A as S, C, D as w, E as T, F as E, I as D, L as O, M as k, N as A, O as j, P as M, S as N, T as P, _ as F, a as I, b as L, c as R, d as z, f as B, g as V, h as H, i as U, j as ne, k as W, l as G, m as K, n as q, o as J, p as Y, r as X, s as Z, t as re, u as ie, v as ae, w as oe, x as se, y as ce } from "./plugin-DOBoUVJ-.js";
3
+ import { a as p, c as m, i as h, l as g, n as _, o as v, r as y, s as b, t as x } from "./strategy-D345j4df.js";
4
+ import { A as S, C, D as w, E as T, F as E, I as D, L as O, M as k, N as A, O as j, P as M, S as N, T as P, _ as F, a as I, b as L, c as R, d as z, f as B, g as V, h as H, i as U, j as ne, k as W, l as G, m as K, n as q, o as J, p as Y, r as X, s as Z, t as re, u as ie, v as ae, w as oe, x as se, y as ce } from "./plugin-CQ_NyxPr.js";
5
5
  import { MAGIC_LINK_TTL_S as le, PASSWORD_RESET_TTL_S as ue, hashToken as de, mintToken as fe } from "./tokens.js";
6
6
  import { CSRF_COOKIE_NAME as pe, CSRF_HEADER_NAME as me, isCsrfTokenWellFormed as Q, issueCsrfToken as he, verifyCsrf as ge } from "./csrf.js";
7
7
  import { generateChallenge as _e, verifyAssertion as ve, verifyRegistration as ye } from "./webauthn.js";
@@ -1,6 +1,6 @@
1
1
  import { hashPassword as e, verifyPassword as t, verifyPasswordWithRehash as n } from "./password.js";
2
2
  import { clearSessionCookie as r, issueSession as i, readSessionKeyed as a, resolveSessionSecret as o, resolveSessionSecrets as s, sessionSecretsOf as c } from "./session.js";
3
- import { a as l, l as u, o as d, s as f, t as p } from "./strategy-CQ2YCIcr.js";
3
+ import { a as l, l as u, o as d, s as f, t as p } from "./strategy-D345j4df.js";
4
4
  import { hashToken as m, mintToken as h } from "./tokens.js";
5
5
  import { CSRF_COOKIE_NAME as g, CSRF_HEADER_NAME as _, issueCsrfToken as v, verifyCsrf as ee } from "./csrf.js";
6
6
  import { generateChallenge as y, verifyAssertion as b, verifyRegistration as te } from "./webauthn.js";
@@ -356,12 +356,13 @@ var ce = { ok: !0 }, C = (e, t) => S.gen(function* () {
356
356
  if (!a) return F(404, { error: "user_not_found" });
357
357
  let o = yield* t.membershipRole(e.userId, e.targetTenantId);
358
358
  if (o === null) return F(403, { error: "not a member of the target tenant" });
359
- let s = yield* t.listMemberships(a.id), c = f(a, {
359
+ let s = yield* t.listMemberships(a.id), c = e.metadata === void 0 ? void 0 : Object.fromEntries(Object.entries(e.metadata).filter(([e]) => e !== "memberships")), l = f(a, {
360
360
  tenantId: e.targetTenantId,
361
- memberships: s
362
- }), l = e.sessionId ? R(c, e.sessionId) : c;
363
- e.clientId !== void 0 && r && r(e.clientId, l);
364
- let u = i(l, N(n), {
361
+ memberships: s,
362
+ ...c === void 0 ? {} : { metadata: c }
363
+ }), u = e.sessionId ? R(l, e.sessionId) : l;
364
+ e.clientId !== void 0 && r && r(e.clientId, u);
365
+ let d = i(u, N(n), {
365
366
  ttlSeconds: L,
366
367
  ...n.cookieDomain ? { domain: n.cookieDomain } : {},
367
368
  secure: n.cookieSecure ?? !0
@@ -370,8 +371,8 @@ var ce = { ok: !0 }, C = (e, t) => S.gen(function* () {
370
371
  ok: !0,
371
372
  tenantId: e.targetTenantId,
372
373
  role: o,
373
- subject: l
374
- }, { setCookie: u.setCookie });
374
+ subject: u
375
+ }, { setCookie: d.setCookie });
375
376
  }), Oe = (e, t) => S.gen(function* () {
376
377
  return F(200, { memberships: (yield* t.listMemberships(e.userId)).map((e) => ({
377
378
  tenantId: e.tenantId,
@@ -701,7 +702,8 @@ var ce = { ok: !0 }, C = (e, t) => S.gen(function* () {
701
702
  userId: t.userId,
702
703
  targetTenantId: Q(a.targetTenantId) ?? "",
703
704
  ...typeof a.clientId == "number" ? { clientId: a.clientId } : {},
704
- ...u?.sessionId ? { sessionId: u.sessionId } : {}
705
+ ...u?.sessionId ? { sessionId: u.sessionId } : {},
706
+ ...d?.type === "user" && d.metadata ? { metadata: d.metadata } : {}
705
707
  }, n, o, e.rebind));
706
708
  }
707
709
  if (e.mfa && i.method === "POST" && m(i, "/mfa/enroll/start")) {
package/dist/plugin.d.ts CHANGED
@@ -203,10 +203,32 @@ declare interface SessionRevocationOptions {
203
203
  * framework never reads it, but app code + the switch-tenant menu do).
204
204
  * Pass an explicit `tenantId` to make the ACTIVE tenant differ from the
205
205
  * user's home tenant (post switch-tenant rebind).
206
+ *
207
+ * `metadata` carries anything else the app needs on the Subject — most
208
+ * often a provider credential captured at login and read back by a
209
+ * plugin's `credentialsResolver` (`subject.metadata.jiraToken` for
210
+ * `@voltro/plugin-atlassian`, say). Without it an app that needs such a
211
+ * credential could not adopt this helper at all: building the Subject by
212
+ * hand was the only way to keep the value.
213
+ *
214
+ * **Precedence, when a `memberships` key appears in BOTH:** the dedicated
215
+ * `memberships` option wins. It is the specific, typed input and it is
216
+ * projected to the `{ tenantId, role }` shape `subjectMemberships` reads,
217
+ * so letting a free-form bag silently shadow it would break the
218
+ * switch-tenant menu in a way nothing type-checks. A `memberships` key
219
+ * inside `metadata` is passed through UNCHANGED when the option is absent
220
+ * — no reshaping, no validation.
221
+ *
222
+ * Note this only stamps the metadata slot at CONSTRUCTION. The sign-in /
223
+ * sign-up / magic-link / passkey handlers later merge `sessionId` (and
224
+ * the password strategy merges `provider`) onto whatever is here, so keys
225
+ * set through this option survive those paths — unless you name a key
226
+ * `sessionId` or `provider`, which those merges overwrite by design.
206
227
  */
207
228
  declare const subjectFromUser: (user: UserRecord, options?: {
208
229
  readonly tenantId?: string;
209
230
  readonly memberships?: ReadonlyArray<MembershipRecord>;
231
+ readonly metadata?: Record<string, unknown>;
210
232
  }) => Subject;
211
233
 
212
234
  /**
package/dist/plugin.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import "./session.js";
2
- import { n as e, t } from "./plugin-DOBoUVJ-.js";
2
+ import { n as e, t } from "./plugin-CQ_NyxPr.js";
3
3
  import "./csrf.js";
4
4
  export { t as authRoutesPlugin, e as getAuthSessionStrategy };
@@ -175,15 +175,18 @@ var s = 3e4, c = 1e4, l = (e, t = {}) => {
175
175
  }, !0);
176
176
  })
177
177
  };
178
- }, m = (e, t = {}) => ({
179
- type: "user",
180
- id: e.id,
181
- tenantId: t.tenantId ?? e.tenantId,
182
- ...t.memberships ? { metadata: { memberships: t.memberships.map((e) => ({
178
+ }, m = (e, t = {}) => {
179
+ let n = { ...t.metadata };
180
+ return t.memberships && (n.memberships = t.memberships.map((e) => ({
183
181
  tenantId: e.tenantId,
184
182
  role: e.role
185
- })) } } : {}
186
- }), h = (e) => {
183
+ }))), {
184
+ type: "user",
185
+ id: e.id,
186
+ tenantId: t.tenantId ?? e.tenantId,
187
+ ...Object.keys(n).length > 0 ? { metadata: n } : {}
188
+ };
189
+ }, h = (e) => {
187
190
  if (e.type !== "user") return null;
188
191
  let t = e.metadata?.sessionId;
189
192
  return typeof t == "string" && t.length > 0 ? t : null;
package/dist/strategy.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import "./session.js";
2
- import { t as e } from "./strategy-CQ2YCIcr.js";
2
+ import { t as e } from "./strategy-D345j4df.js";
3
3
  export { e as voltroPasswordStrategy };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/plugin-auth",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Authentication primitives: password hashing, session creation, schema mixin + tables. Pairs with the `auth` app template for the UI; both independently usable. Server-side only (uses node:crypto).",
5
5
  "keywords": [
6
6
  "voltro",
@@ -78,8 +78,8 @@
78
78
  },
79
79
  "dependencies": {
80
80
  "@effect/sql": "^0.51.1",
81
- "@voltro/database": "0.6.0",
82
- "@voltro/protocol": "0.6.0"
81
+ "@voltro/database": "0.7.0",
82
+ "@voltro/protocol": "0.7.0"
83
83
  },
84
84
  "peerDependencies": {
85
85
  "effect": "^3.21.4",