or3-provider-basic-auth 0.0.21 → 0.0.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.
package/README.md CHANGED
@@ -245,8 +245,8 @@ Strict-mode behavior:
245
245
  - Invite links (`/?invite=TOKEN`, copied from Admin → Workspaces, or carried in the lock page's `next`) open registration for signed-out visitors with the token filled in. The token is removed from the address bar on first read and kept in memory for that page; only one mounted auth control (sidebar, mobile More sheet or lock page) opens registration per link. On mobile the account control lives in More, so registration opens when the visitor opens More. This invite-link handoff requires published `or3-provider-basic-auth@0.0.11` or later.
246
246
  - Basic Auth account and initial refresh-session rows are created in one local SQLite transaction.
247
247
  - Access JWTs are short-lived and validated by `basicAuthProvider.getSession(event)`.
248
- - Refresh tokens are rotated and hashed at rest; replay attempts revoke active sessions.
249
- - The refresh cookie is scoped to `/api` so `/api/auth/session` can transparently rotate expired access tokens during session resolution.
248
+ - Each refresh rotates the session atomically. A second tab can recover the same successor during the grace period by presenting the matching HttpOnly `or3_refresh_proof` cookie. A verified replay after that period revokes the account’s active sessions.
249
+ - Both refresh cookies are scoped to `/api` so `/api/auth/session` can renew an expired access token. Existing active sessions obtain their proof cookie on their next refresh.
250
250
  - Sign-out never refreshes the session: the user is resolved without rotation, and revoking a token also revokes the sessions it was rotated into and clears their rotation grace, so a replayed predecessor cannot recover a successor after logout.
251
251
  - The SQLite DB file and directory are hardened to mode `0600`/`0700`; the DB uses WAL journaling.
252
252
 
@@ -336,6 +336,9 @@ or failed builds fall back to installed packages with a warning.
336
336
  `OR3_LOCAL_PROVIDERS=false` disables local selection. Production builds use the
337
337
  installed package, so local development does not publish these changes.
338
338
 
339
+ Manual runs of **Publish npm package** qualify the selected revision. To
340
+ publish the qualified tarball, push a `v<version>` tag matching `package.json`.
341
+
339
342
  Basic Auth's database always uses `better-sqlite3`, independently of the sync
340
343
  provider's SQLite driver. If the source launcher selects Bun for sync, this
341
344
  native binding must also work under the project-pinned Bun version. The launcher
@@ -344,9 +347,9 @@ or runtime crashes. Managed Cloud uses Node with `better-sqlite3`.
344
347
 
345
348
  ## Instance signup invitations
346
349
 
347
- The updated host distinguishes signup invites from existing team invites. Signup invites create a private workspace with only the recipient as owner; team invites retain their selected workspace and role. This requires the updated host and rebuilt provider artifacts, rather than the existing published release alone.
350
+ The updated host distinguishes signup invites from existing team invites. Signup invites create a private workspace for the recipient. A team invite also grants the chosen role in the shared workspace. When someone joins from a link or registration form, their first chat opens in their private workspace. They can select the joined team from the workspace switcher. This requires the updated host and rebuilt provider artifacts, rather than the existing published release alone.
348
351
 
349
- Registration preflight rejects invalid invites before credential creation, including in open mode. It resolves the explicit body token first, followed by the host's header, HttpOnly cookie, query, and Referer precedence. A valid token is retained in the invite cookie for canonical session resolution; an explicit replacement overrides a stale cookie. Without a token, open registration remains available. If credentials commit before canonical acceptance, use Already registered? Sign in with the same account and a valid or replacement invite. The sign-in request preserves manually pasted tokens, verifies the signed-in email, and uses the existing HttpOnly invite cookie. The selected sync store still owns atomic acceptance; provider-only credentials grant no protected OR3 access. No credential lifecycle or recovery service is added.
352
+ Registration preflight rejects invalid invites before credential creation, including in open mode. It resolves the explicit body token first, followed by the host's header, HttpOnly cookie, query, and same-origin Referer. An open instance clears a retained team-link cookie when another account registers. That account receives its own private workspace. A valid token is retained in the invite cookie for canonical session resolution; an explicit replacement overrides a stale cookie. Without a token, open registration remains available. If credentials commit before canonical acceptance, use Already registered? Sign in with the same account and a valid or replacement invite. The sign-in request preserves manually pasted tokens, verifies the signed-in email, and uses the existing HttpOnly invite cookie. The selected sync store still owns atomic acceptance; provider-only credentials grant no protected OR3 access. No credential lifecycle or recovery service is added.
350
353
 
351
354
  Provider-only tests use the exact host registration and token sources pinned in `tests/fixtures/host`, with SHA-256 provenance verified by Vitest. No sibling checkout is required. To exercise the current host integration, run `OR3_CANONICAL_HOST_ROOT=/absolute/path/to/or3-chat bun run test`. Refresh the pinned files and provenance together when adopting a reviewed host contract change; do not replace the host validation logic with a provider-local implementation.
352
355
 
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "or3-provider-basic-auth",
3
3
  "configKey": "or3-provider-basic-auth",
4
- "version": "0.0.21",
4
+ "version": "0.0.22",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -78,6 +78,7 @@ export async function handleRegister(event) {
78
78
  mapRegistrationErrorToHttp("disabled", mode);
79
79
  }
80
80
  const inviteToken = body.inviteToken ?? getInviteTokenFromEvent(event);
81
+ let inviteCookie = inviteToken;
81
82
  if (mode === "invite_only" && !inviteToken) {
82
83
  mapRegistrationErrorToHttp("invite_required", mode);
83
84
  }
@@ -93,11 +94,12 @@ export async function handleRegister(event) {
93
94
  store,
94
95
  mode,
95
96
  email,
96
- inviteToken
97
+ inviteToken: body.inviteToken
97
98
  });
98
99
  if (!decision.allowed) {
99
100
  mapRegistrationErrorToHttp(decision.reason, mode);
100
101
  }
102
+ inviteCookie = decision.invite ? decision.invite.cookieValue ?? decision.invite.token : null;
101
103
  }
102
104
  const existing = findAccountByEmail(email);
103
105
  if (existing) {
@@ -139,8 +141,8 @@ export async function handleRegister(event) {
139
141
  });
140
142
  setAccessCookie(event, accessToken, config.accessTtlSeconds);
141
143
  setRefreshCookie(event, refreshToken, config.refreshTtlSeconds);
142
- if (inviteToken) {
143
- setCookie(event, "or3_invite_token", inviteToken, {
144
+ if (inviteCookie) {
145
+ setCookie(event, "or3_invite_token", inviteCookie, {
144
146
  httpOnly: true,
145
147
  sameSite: "lax",
146
148
  secure: process.env.NODE_ENV === "production",
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { defineEventHandler, setCookie } from "h3";
2
+ import { defineEventHandler, getHeader, setCookie } from "h3";
3
3
  import { useRuntimeConfig } from "#imports";
4
4
  import { resolveRegistrationMode, validateInviteRegistration } from "~~/server/auth/registration";
5
5
  import { getAuthWorkspaceStore } from "~~/server/auth/store/registry";
@@ -48,8 +48,9 @@ export async function handleSignIn(event) {
48
48
  }
49
49
  const runtimeConfig = useRuntimeConfig();
50
50
  const syncConfig = runtimeConfig;
51
- const store = input.inviteToken ? getAuthWorkspaceStore(syncConfig.sync?.provider ?? syncConfig.public?.sync?.provider ?? "convex") : null;
52
- const invitation = input.inviteToken && store ? await validateInviteRegistration({ event, store, mode: resolveRegistrationMode(runtimeConfig), email, inviteToken: input.inviteToken }) : null;
51
+ const inviteToken = input.inviteToken ?? getHeader(event, "x-or3-invite-token")?.trim();
52
+ const store = inviteToken ? getAuthWorkspaceStore(syncConfig.sync?.provider ?? syncConfig.public?.sync?.provider ?? "convex") : null;
53
+ const invitation = inviteToken && store ? await validateInviteRegistration({ event, store, mode: resolveRegistrationMode(runtimeConfig), email, inviteToken }) : null;
53
54
  const config = getBasicAuthConfig();
54
55
  if (config.refreshTtlSeconds <= 0 || config.accessTtlSeconds <= 0) {
55
56
  throw createInvalidRequestError();
@@ -77,7 +78,7 @@ export async function handleSignIn(event) {
77
78
  setAccessCookie(event, accessToken, config.accessTtlSeconds);
78
79
  setRefreshCookie(event, refreshToken, config.refreshTtlSeconds);
79
80
  if (invitation?.allowed && invitation.invite) {
80
- setCookie(event, "or3_invite_token", input.inviteToken, {
81
+ setCookie(event, "or3_invite_token", invitation.invite.cookieValue ?? invitation.invite.token, {
81
82
  httpOnly: true,
82
83
  sameSite: "lax",
83
84
  secure: process.env.NODE_ENV === "production",
@@ -1,6 +1,8 @@
1
1
  import { type H3Event } from 'h3';
2
2
  export declare function accessCookieName(): string;
3
3
  export declare function refreshCookieName(): string;
4
+ /** Only a browser issued both cookies can recover an already-rotated refresh token. */
5
+ export declare function hasRefreshGraceProof(event: H3Event, token: string): boolean;
4
6
  export declare function setAccessCookie(event: H3Event, token: string, maxAgeSeconds: number): void;
5
7
  export declare function setRefreshCookie(event: H3Event, token: string, maxAgeSeconds: number): void;
6
8
  export declare function clearAuthCookies(event: H3Event): void;
@@ -1,4 +1,6 @@
1
- import { setCookie, deleteCookie } from "h3";
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { setCookie, getCookie, deleteCookie } from "h3";
3
+ import { getBasicAuthConfig } from "./config.js";
2
4
  import {
3
5
  ACCESS_COOKIE_NAME,
4
6
  ACCESS_COOKIE_PATH,
@@ -6,16 +8,27 @@ import {
6
8
  REFRESH_COOKIE_NAME,
7
9
  REFRESH_COOKIE_PATH
8
10
  } from "../../lib/constants.js";
11
+ const REFRESH_PROOF_COOKIE_NAME = "or3_refresh_proof";
9
12
  function isProduction() {
10
13
  return process.env.NODE_ENV === "production";
11
14
  }
12
- export function accessCookieName() {
15
+ function scopedCookieName(name) {
13
16
  const scope = process.env.OR3_PLUGIN_DEV_COOKIE_SCOPE;
14
- return scope ? `${ACCESS_COOKIE_NAME}_${scope}` : ACCESS_COOKIE_NAME;
17
+ return scope ? `${name}_${scope}` : name;
18
+ }
19
+ export function accessCookieName() {
20
+ return scopedCookieName(ACCESS_COOKIE_NAME);
15
21
  }
16
22
  export function refreshCookieName() {
17
- const scope = process.env.OR3_PLUGIN_DEV_COOKIE_SCOPE;
18
- return scope ? `${REFRESH_COOKIE_NAME}_${scope}` : REFRESH_COOKIE_NAME;
23
+ return scopedCookieName(REFRESH_COOKIE_NAME);
24
+ }
25
+ function refreshProof(token) {
26
+ return createHmac("sha256", getBasicAuthConfig().refreshSecret).update("or3-basic-auth:refresh-grace-proof:v1:").update(token).digest("base64url");
27
+ }
28
+ export function hasRefreshGraceProof(event, token) {
29
+ const proof = getCookie(event, scopedCookieName(REFRESH_PROOF_COOKIE_NAME));
30
+ if (!proof || Buffer.byteLength(proof) !== 43) return false;
31
+ return timingSafeEqual(Buffer.from(proof), Buffer.from(refreshProof(token)));
19
32
  }
20
33
  function refreshCookieBase() {
21
34
  return {
@@ -38,11 +51,9 @@ export function setRefreshCookie(event, token, maxAgeSeconds) {
38
51
  ...refreshCookieBase(),
39
52
  path: LEGACY_REFRESH_COOKIE_PATH
40
53
  });
41
- setCookie(event, refreshCookieName(), token, {
42
- ...refreshCookieBase(),
43
- path: REFRESH_COOKIE_PATH,
44
- maxAge: maxAgeSeconds
45
- });
54
+ const options = { ...refreshCookieBase(), path: REFRESH_COOKIE_PATH, maxAge: maxAgeSeconds };
55
+ setCookie(event, refreshCookieName(), token, options);
56
+ setCookie(event, scopedCookieName(REFRESH_PROOF_COOKIE_NAME), refreshProof(token), options);
46
57
  }
47
58
  export function clearAuthCookies(event) {
48
59
  deleteCookie(event, accessCookieName(), {
@@ -51,10 +62,9 @@ export function clearAuthCookies(event) {
51
62
  secure: isProduction(),
52
63
  path: ACCESS_COOKIE_PATH
53
64
  });
54
- deleteCookie(event, refreshCookieName(), {
55
- ...refreshCookieBase(),
56
- path: REFRESH_COOKIE_PATH
57
- });
65
+ const options = { ...refreshCookieBase(), path: REFRESH_COOKIE_PATH };
66
+ deleteCookie(event, refreshCookieName(), options);
67
+ deleteCookie(event, scopedCookieName(REFRESH_PROOF_COOKIE_NAME), options);
58
68
  deleteCookie(event, refreshCookieName(), {
59
69
  ...refreshCookieBase(),
60
70
  path: LEGACY_REFRESH_COOKIE_PATH
@@ -1,6 +1,6 @@
1
1
  import type { H3Event } from 'h3';
2
2
  import type { BasicAuthAccount } from '../db/schema.js';
3
- export type RefreshAuthSessionFailureReason = 'missing_token' | 'invalid_token' | 'account' | 'not_found' | 'expired' | 'revoked' | 'replayed';
3
+ export type RefreshAuthSessionFailureReason = 'missing_token' | 'invalid_token' | 'account' | 'not_found' | 'expired' | 'revoked' | 'replayed' | 'stale';
4
4
  export type RefreshAuthSessionResult = {
5
5
  ok: true;
6
6
  account: BasicAuthAccount;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { clearAuthCookies, setAccessCookie, setRefreshCookie } from "./cookies.js";
2
+ import { clearAuthCookies, hasRefreshGraceProof, setAccessCookie, setRefreshCookie } from "./cookies.js";
3
3
  import { getBasicAuthConfig } from "./config.js";
4
4
  import {
5
5
  getRefreshTokenFromEvent,
@@ -36,6 +36,7 @@ export async function refreshAuthSession(event) {
36
36
  const rotation = rotateSession({
37
37
  currentSessionId: claims.sid,
38
38
  currentRefreshHash: hashRefreshToken(refreshToken),
39
+ hasGraceProof: hasRefreshGraceProof(event, refreshToken),
39
40
  newSessionId,
40
41
  newRefreshHash: hashRefreshToken(newRefreshToken),
41
42
  newRefreshToken,
@@ -71,7 +72,7 @@ export async function refreshAuthSessionAndSetCookies(event, options = {}) {
71
72
  const clearOnFailure = options.clearOnFailure ?? true;
72
73
  const result = await refreshAuthSession(event);
73
74
  if (!result.ok) {
74
- if (clearOnFailure) {
75
+ if (clearOnFailure && result.reason !== "stale") {
75
76
  clearAuthCookies(event);
76
77
  }
77
78
  return result;
@@ -21,6 +21,8 @@ export interface CreateSessionInput {
21
21
  export interface RotationInput {
22
22
  currentSessionId: string;
23
23
  currentRefreshHash: string;
24
+ /** Verified for this predecessor, required only after its first rotation. */
25
+ hasGraceProof?: boolean;
24
26
  newSessionId: string;
25
27
  newRefreshHash: string;
26
28
  /** Plaintext successor refresh token; sealed into the grace window for concurrent reuse. */
@@ -41,7 +43,7 @@ export type RotationResult = {
41
43
  refreshToken?: string;
42
44
  } | {
43
45
  ok: false;
44
- reason: 'not_found' | 'expired' | 'revoked' | 'replayed';
46
+ reason: 'not_found' | 'expired' | 'revoked' | 'replayed' | 'stale';
45
47
  };
46
48
  export declare function normalizeEmail(email: string): string;
47
49
  export declare function getSessionMetadataFromEvent(event: H3Event): SessionMetadata;
@@ -21,14 +21,6 @@ function safeHexEquals(left, right) {
21
21
  if (leftBuffer.length !== rightBuffer.length) return false;
22
22
  return timingSafeEqual(leftBuffer, rightBuffer);
23
23
  }
24
- function clearExpiredRotationGrace(sessionId) {
25
- const db = getBasicAuthDb();
26
- db.prepare(
27
- `UPDATE basic_auth_sessions
28
- SET rotation_grace_until = NULL, rotation_grace_refresh_token = NULL
29
- WHERE id = ?`
30
- ).run(sessionId);
31
- }
32
24
  export function getSessionMetadataFromEvent(event) {
33
25
  const proxyConfig = normalizeProxyTrustConfig(useRuntimeConfig(event).security?.proxy);
34
26
  return {
@@ -180,67 +172,49 @@ export function revokeAllSessionsForAccount(accountId, revokedAtMs = Date.now())
180
172
  WHERE account_id = ?`
181
173
  ).run(revokedAtMs, accountId);
182
174
  }
183
- function tryReuseRotatedSession(currentSession, isSameTokenHash, now) {
184
- if (currentSession.replaced_by_session_id === null || !isSameTokenHash) {
185
- return null;
175
+ function recoverRotatedSession(session, isSameTokenHash, hasGraceProof, now) {
176
+ if (!session.replaced_by_session_id || !isSameTokenHash) {
177
+ return { ok: false, reason: "revoked" };
186
178
  }
187
- const graceUntil = currentSession.rotation_grace_until;
188
- const sealedToken = currentSession.rotation_grace_refresh_token;
189
- if (typeof graceUntil === "number" && graceUntil > now && typeof sealedToken === "string" && sealedToken.length > 0) {
190
- const refreshToken = unsealRotationGraceToken(sealedToken);
191
- const successor = findSessionById(currentSession.replaced_by_session_id);
192
- if (refreshToken && successor && isSessionUsable(successor)) {
193
- return {
194
- ok: true,
195
- reused: true,
196
- accountId: currentSession.account_id,
197
- sessionId: successor.id,
198
- refreshToken
199
- };
200
- }
179
+ if (!hasGraceProof) return { ok: false, reason: "stale" };
180
+ if (session.rotation_grace_until === null || !session.rotation_grace_refresh_token) {
181
+ return { ok: false, reason: "revoked" };
201
182
  }
202
- clearExpiredRotationGrace(currentSession.id);
203
- return null;
183
+ if (session.rotation_grace_until <= now) {
184
+ revokeAllSessionsForAccount(session.account_id, now);
185
+ return { ok: false, reason: "replayed" };
186
+ }
187
+ const successor = findSessionById(session.replaced_by_session_id);
188
+ if (!isSessionUsable(successor)) return { ok: false, reason: "stale" };
189
+ const refreshToken = unsealRotationGraceToken(session.rotation_grace_refresh_token);
190
+ if (!refreshToken) return { ok: false, reason: "stale" };
191
+ return {
192
+ ok: true,
193
+ reused: true,
194
+ accountId: session.account_id,
195
+ sessionId: session.replaced_by_session_id,
196
+ refreshToken
197
+ };
204
198
  }
205
199
  export function rotateSession(input) {
206
200
  const db = getBasicAuthDb();
207
- const now = input.nowMs ?? Date.now();
208
- const graceMs = input.graceMs ?? REFRESH_ROTATION_GRACE_MS;
209
- const currentSession = findSessionById(input.currentSessionId);
210
- if (!currentSession) {
211
- return { ok: false, reason: "not_found" };
212
- }
213
- if (currentSession.expires_at <= now) {
214
- revokeSessionById(currentSession.id, now);
215
- return { ok: false, reason: "expired" };
216
- }
217
- const isSameTokenHash = safeHexEquals(
218
- currentSession.refresh_token_hash,
219
- input.currentRefreshHash
220
- );
221
- if (currentSession.revoked_at !== null) {
222
- const reused = tryReuseRotatedSession(currentSession, isSameTokenHash, now);
223
- if (reused) {
224
- return reused;
201
+ return db.transaction(() => {
202
+ const now = input.nowMs ?? Date.now();
203
+ const currentSession = findSessionById(input.currentSessionId);
204
+ if (!currentSession) return { ok: false, reason: "not_found" };
205
+ if (currentSession.expires_at <= now) {
206
+ revokeSessionById(currentSession.id, now);
207
+ return { ok: false, reason: "expired" };
208
+ }
209
+ const isSameTokenHash = safeHexEquals(currentSession.refresh_token_hash, input.currentRefreshHash);
210
+ if (currentSession.revoked_at !== null) {
211
+ return recoverRotatedSession(currentSession, isSameTokenHash, input.hasGraceProof === true, now);
225
212
  }
226
- if (currentSession.replaced_by_session_id !== null && isSameTokenHash) {
213
+ if (!isSameTokenHash) {
227
214
  revokeAllSessionsForAccount(currentSession.account_id, now);
228
- return {
229
- ok: false,
230
- reason: "replayed"
231
- };
215
+ return { ok: false, reason: "replayed" };
232
216
  }
233
- return { ok: false, reason: "revoked" };
234
- }
235
- if (!isSameTokenHash) {
236
- revokeAllSessionsForAccount(currentSession.account_id, now);
237
- return {
238
- ok: false,
239
- reason: "replayed"
240
- };
241
- }
242
- const sealedGraceToken = sealRotationGraceToken(input.newRefreshToken);
243
- db.transaction(() => {
217
+ const sealedGraceToken = sealRotationGraceToken(input.newRefreshToken);
244
218
  createAuthSession({
245
219
  accountId: currentSession.account_id,
246
220
  sessionId: input.newSessionId,
@@ -249,6 +223,7 @@ export function rotateSession(input) {
249
223
  rotatedFromSessionId: currentSession.id,
250
224
  metadata: input.metadata
251
225
  });
226
+ const graceMs = input.graceMs ?? REFRESH_ROTATION_GRACE_MS;
252
227
  db.prepare(
253
228
  `UPDATE basic_auth_sessions
254
229
  SET revoked_at = ?,
@@ -257,13 +232,13 @@ export function rotateSession(input) {
257
232
  rotation_grace_refresh_token = ?
258
233
  WHERE id = ?`
259
234
  ).run(now, input.newSessionId, now + graceMs, sealedGraceToken, currentSession.id);
260
- })();
261
- return {
262
- ok: true,
263
- reused: false,
264
- accountId: currentSession.account_id,
265
- sessionId: input.newSessionId
266
- };
235
+ return {
236
+ ok: true,
237
+ reused: false,
238
+ accountId: currentSession.account_id,
239
+ sessionId: input.newSessionId
240
+ };
241
+ }).immediate();
267
242
  }
268
243
  export function updatePasswordAndRevokeSessions(accountId, newPasswordHash) {
269
244
  const db = getBasicAuthDb();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-basic-auth",
3
- "version": "0.0.21",
3
+ "version": "0.0.22",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-basic-auth.git"