@fayz-ai/auth 0.18.0 → 0.21.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.
@@ -1 +1 @@
1
- {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/adapters/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAA;AACzE,OAAO,KAAK,EAAE,WAAW,EAAuC,MAAM,eAAe,CAAA;AAGrF;;;mEAGmE;AACnE,eAAO,MAAM,sBAAsB,2BAA2B,CAAA;AAE9D,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,MAAM,CAAA;IACnB,eAAe,EAAE,MAAM,CAAA;IACvB,cAAc,CAAC,EAAE,cAAc,CAAA;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAwCD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,kBAAkB,GAAG,WAAW,CAgLjF"}
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/adapters/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAA;AACzE,OAAO,KAAK,EAAE,WAAW,EAAuC,MAAM,eAAe,CAAA;AAGrF;;;mEAGmE;AACnE,eAAO,MAAM,sBAAsB,2BAA2B,CAAA;AAE9D,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,MAAM,CAAA;IACnB,eAAe,EAAE,MAAM,CAAA;IACvB,cAAc,CAAC,EAAE,cAAc,CAAA;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAwCD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,kBAAkB,GAAG,WAAW,CAgMjF"}
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","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MAAM,eAAe,CAAA;AAmC5F,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,WAAW,CAAA;IACpB,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CAC1B;AAED,wBAAgB,YAAY,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,iBAAiB,qBA4LpE;AAMD,wBAAgB,OAAO;;;;;;;;;oBA3NL,MAAM,YAAY,MAAM,KAAK,OAAO,CAAC,WAAW,CAAC;oBACjD,MAAM,YAAY,MAAM,YAAY,MAAM,KAAK,OAAO,CAAC,WAAW,CAAC;mBACpE,OAAO,CAAC,IAAI,CAAC;gCACA,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC;2BACpC,MAAM,YAAY;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC;+BACvD,MAAM,KAAK,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;2BAC1C,MAAM,KAAK,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;wBACzC,MAAM,YAAY;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC;gCAEnF,MAAM,YAAY;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,OAAO,CAAC;oCAE1D,IAAI;EA0OrC"}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { createSupabaseAuthAdapter, MUST_SET_PASSWORD_FLAG } from './adapters/supabase';
2
2
  export type { SupabaseAuthConfig } from './adapters/supabase';
3
- export { readAuthUrlIntent, clearAuthUrlTokens, withAuthIntent, decidePasswordSetup, AUTH_INTENT_PARAM, } from './lib/url-intent';
4
- export type { AuthUrlIntent, PasswordSetupDecision, PasswordSetupInput, PasswordSetupReason, } from './lib/url-intent';
3
+ export { readAuthUrlIntent, clearAuthUrlTokens, withAuthIntent, decidePasswordSetup, AUTH_INTENT_PARAM, readAppHandoff, buildAppHandoffUrl, APP_HANDOFF_PARAM, APP_HANDOFF_REFRESH_PARAM, APP_HANDOFF_TENANT_PARAM, } from './lib/url-intent';
4
+ export type { AppHandoff, AuthUrlIntent, PasswordSetupDecision, PasswordSetupInput, PasswordSetupReason, } from './lib/url-intent';
5
5
  export { createMockAuthAdapter } from './adapters/mock';
6
6
  export type { MockUser } from './adapters/mock';
7
7
  export { useAuthStore } from './store';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AACvF,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAG7D,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,kBAAkB,CAAA;AACzB,YAAY,EACV,aAAa,EACb,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;AACvD,YAAY,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AAG/C,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAGnD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACjD,YAAY,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AACvF,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAG7D,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,kBAAkB,EAClB,iBAAiB,EACjB,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,kBAAkB,CAAA;AACzB,YAAY,EACV,UAAU,EACV,aAAa,EACb,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;AACvD,YAAY,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AAG/C,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAGnD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACjD,YAAY,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA"}
package/dist/index.js CHANGED
@@ -9,11 +9,12 @@ import { jsx } from 'react/jsx-runtime';
9
9
  var AUTH_INTENT_PARAM = "fayz_auth";
10
10
  var RESET_PATH = "/auth/reset-password";
11
11
  function snapshot() {
12
- if (typeof window === "undefined") return null;
12
+ const loc = typeof window === "undefined" ? void 0 : window.location;
13
+ if (!loc) return null;
13
14
  return {
14
- pathname: window.location.pathname,
15
- search: window.location.search,
16
- hash: window.location.hash
15
+ pathname: loc.pathname ?? "",
16
+ search: loc.search ?? "",
17
+ hash: loc.hash ?? ""
17
18
  };
18
19
  }
19
20
  var initialUrl = snapshot();
@@ -40,6 +41,31 @@ function readAuthUrlIntent(url) {
40
41
  if (path.endsWith(RESET_PATH)) return { kind: "recovery" };
41
42
  return null;
42
43
  }
44
+ var APP_HANDOFF_PARAM = "handoff";
45
+ var APP_HANDOFF_REFRESH_PARAM = "handoff_r";
46
+ var APP_HANDOFF_TENANT_PARAM = "account";
47
+ function readAppHandoff(url) {
48
+ const loc = url ?? initialUrl;
49
+ if (!loc) return null;
50
+ const hash = hashParams(loc.hash);
51
+ const accessToken = hash.get(APP_HANDOFF_PARAM);
52
+ const refreshToken = hash.get(APP_HANDOFF_REFRESH_PARAM);
53
+ if (!accessToken || !refreshToken) return null;
54
+ return {
55
+ accessToken,
56
+ refreshToken,
57
+ tenantId: hash.get(APP_HANDOFF_TENANT_PARAM) || null
58
+ };
59
+ }
60
+ function buildAppHandoffUrl(appUrl, session, tenantId) {
61
+ if (!session.accessToken || !session.refreshToken) return appUrl;
62
+ const params = new URLSearchParams();
63
+ params.set(APP_HANDOFF_PARAM, session.accessToken);
64
+ params.set(APP_HANDOFF_REFRESH_PARAM, session.refreshToken);
65
+ if (tenantId) params.set(APP_HANDOFF_TENANT_PARAM, tenantId);
66
+ const base = appUrl.split("#")[0];
67
+ return `${base}#${params.toString()}`;
68
+ }
43
69
  function clearAuthUrlTokens() {
44
70
  if (typeof window === "undefined") return;
45
71
  const url = new URL(window.location.href);
@@ -110,6 +136,21 @@ function createSupabaseAuthAdapter(config) {
110
136
  if (error) throw error;
111
137
  return mapSupabaseSession(data.session);
112
138
  },
139
+ /**
140
+ * Adopt a session handed over by a sibling application (see url-intent).
141
+ *
142
+ * `setSession` is the verification, not a formality: GoTrue validates the
143
+ * tokens and rotates the refresh token, so a forged or replayed fragment
144
+ * fails here rather than being trusted because it looked well-formed.
145
+ */
146
+ async adoptSession(accessToken, refreshToken) {
147
+ const { data, error } = await supabase.auth.setSession({
148
+ access_token: accessToken,
149
+ refresh_token: refreshToken
150
+ });
151
+ if (error || !data.session) return null;
152
+ return mapSupabaseSession(data.session);
153
+ },
113
154
  async signUp(email, password, fullName) {
114
155
  const { data, error } = await supabase.auth.signUp({
115
156
  email,
@@ -358,7 +399,14 @@ function AuthProvider({ adapter, children }) {
358
399
  async function init() {
359
400
  try {
360
401
  setLoading(true);
361
- const result = await adapterRef.current.getSession();
402
+ const handoff = readAppHandoff();
403
+ const adopt = adapterRef.current.adoptSession;
404
+ let adopted = null;
405
+ if (handoff && typeof adopt === "function") {
406
+ adopted = await adopt.call(adapterRef.current, handoff.accessToken, handoff.refreshToken);
407
+ clearAuthUrlTokens();
408
+ }
409
+ const result = adopted ? { session: adopted } : await adapterRef.current.getSession();
362
410
  setSession(result?.session ?? null);
363
411
  } catch (err) {
364
412
  setError(err instanceof Error ? err : new Error(String(err)));
@@ -520,6 +568,6 @@ function useAuth() {
520
568
  };
521
569
  }
522
570
 
523
- export { AUTH_INTENT_PARAM, AuthProvider, MUST_SET_PASSWORD_FLAG, clearAuthUrlTokens, createMockAuthAdapter, createSupabaseAuthAdapter, decidePasswordSetup, readAuthUrlIntent, useAuth, useAuthStore, withAuthIntent };
571
+ export { APP_HANDOFF_PARAM, APP_HANDOFF_REFRESH_PARAM, APP_HANDOFF_TENANT_PARAM, AUTH_INTENT_PARAM, AuthProvider, MUST_SET_PASSWORD_FLAG, buildAppHandoffUrl, clearAuthUrlTokens, createMockAuthAdapter, createSupabaseAuthAdapter, decidePasswordSetup, readAppHandoff, readAuthUrlIntent, useAuth, useAuthStore, withAuthIntent };
524
572
  //# sourceMappingURL=index.js.map
525
573
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/url-intent.ts","../src/adapters/supabase.ts","../src/adapters/mock.ts","../src/store.ts","../src/context.tsx"],"names":[],"mappings":";;;;;;;;AA2BO,IAAM,iBAAA,GAAoB;AAIjC,IAAM,UAAA,GAAa,sBAAA;AAQnB,SAAS,QAAA,GAA+B;AACtC,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,IAAA;AAC1C,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,OAAO,QAAA,CAAS,QAAA;AAAA,IAC1B,MAAA,EAAQ,OAAO,QAAA,CAAS,MAAA;AAAA,IACxB,IAAA,EAAM,OAAO,QAAA,CAAS;AAAA,GACxB;AACF;AAGA,IAAM,aAAiC,QAAA,EAAS;AAIhD,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AQ,GAAA,GAAM,IAAI,KAAA,CAAM,MAAA,CAAO,GAAG,CAAC,CAAA;AAChE,QAAA,QAAA,CAAS,KAAK,CAAA;AACd,QAAA,MAAM,KAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,IAEA,wBAAA,GAA2B;AACzB,MAAA,sBAAA,CAAuB,IAAI,CAAA;AAC3B,MAAA,QAAA,CAAS,IAAI,CAAA;AAAA,IACf;AAAA,GACF;AAEA,EAAA,uBAAO,GAAA,CAAC,WAAA,CAAY,QAAA,EAAZ,EAAqB,OAAe,QAAA,EAAS,CAAA;AACvD;AAMO,SAAS,OAAA,GAAU;AACxB,EAAA,MAAM,GAAA,GAAM,WAAW,WAAW,CAAA;AAClC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,4CAA4C,CAAA;AAAA,EAC9D;AAEA,EAAA,MAAM,EAAE,MAAM,OAAA,EAAS,SAAA,EAAW,iBAAiB,KAAA,EAAO,mBAAA,KAAwB,YAAA,EAAa;AAE/F,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,OAAA;AAAA,IACA,SAAA;AAAA,IACA,eAAA;AAAA,IACA,KAAA;AAAA,IACA,mBAAA;AAAA,IACA,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,iBAAiB,GAAA,CAAI,eAAA;AAAA,IACrB,eAAe,GAAA,CAAI,aAAA;AAAA,IACnB,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,YAAY,GAAA,CAAI,UAAA;AAAA,IAChB,oBAAoB,GAAA,CAAI,kBAAA;AAAA,IACxB,0BAA0B,GAAA,CAAI;AAAA,GAChC;AACF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Auth link intent — what the URL the user just arrived on is asking for.\n//\n// A Supabase recovery / magic link lands on the app with the tokens in the URL\n// FRAGMENT (implicit flow is the supabase-js default), e.g.\n//\n// https://app.example.com/#access_token=…&refresh_token=…&type=recovery\n//\n// GoTrue then consumes that fragment and wipes it (`window.location.hash = ''`)\n// as soon as the client initialises — so by the time React renders, the reason\n// the user is here is gone. Hence the module-load snapshot: this file is\n// imported long before any createClient() call, so it always sees the original\n// URL.\n//\n// Errors arrive the same way, without a `type`:\n//\n// https://app.example.com/#error=access_denied&error_code=otp_expired&…\n// ---------------------------------------------------------------------------\n\nexport type AuthUrlIntent =\n /** A password-recovery link — the user must choose a new password now. */\n | { kind: 'recovery' }\n /** A one-time link that was already used or has expired. */\n | { kind: 'expired'; message?: string }\n\n/** Query param apps can put on their own redirect URLs to force the\n * set-password screen (e.g. when they override `resetPasswordUrl`). */\nexport const AUTH_INTENT_PARAM = 'fayz_auth'\n\n/** Path segment the SDK historically used as the reset-password redirect.\n * Still honoured so apps that configured it keep working. */\nconst RESET_PATH = '/auth/reset-password'\n\ninterface UrlSnapshot {\n pathname: string\n search: string\n hash: string\n}\n\nfunction snapshot(): UrlSnapshot | null {\n if (typeof window === 'undefined') return null\n return {\n pathname: window.location.pathname,\n search: window.location.search,\n hash: window.location.hash,\n }\n}\n\n/** Taken at import time — before any Supabase client can strip the fragment. */\nconst initialUrl: UrlSnapshot | null = snapshot()\n\n/** The fragment can be either auth params (`access_token=…&type=recovery`) or a\n * hash-router path (`#/dashboard`). Only the former parses into pairs. */\nfunction hashParams(hash: string): URLSearchParams {\n const raw = hash.replace(/^#/, '')\n if (!raw || !raw.includes('=')) return new URLSearchParams()\n return new URLSearchParams(raw)\n}\n\nexport function readAuthUrlIntent(url?: UrlSnapshot | null): AuthUrlIntent | null {\n const loc = url ?? initialUrl\n if (!loc) return null\n\n const query = new URLSearchParams(loc.search)\n const hash = hashParams(loc.hash)\n const param = (key: string) => hash.get(key) ?? query.get(key)\n\n const errorCode = param('error_code') ?? param('error')\n const errorDescription = param('error_description')?.replace(/\\+/g, ' ')\n // A dead one-time link (`error_code=otp_expired`). Deliberately narrow: an\n // OAuth `access_denied` is a different failure and must not land here. GoTrue\n // does not echo `type` on error redirects, so recovery and invite links are\n // indistinguishable at this point — the screen offers a fresh link either way.\n if (errorCode && /otp|expired|link/i.test(`${errorCode} ${errorDescription ?? ''}`)) {\n return { kind: 'expired', message: errorDescription ?? undefined }\n }\n\n const marker = query.get(AUTH_INTENT_PARAM)\n const type = param('type')\n if (type === 'recovery' || marker === 'recovery') return { kind: 'recovery' }\n\n // `/auth/reset-password` with no tokens at all: the user opened the reset URL\n // directly, or the tokens were already consumed by a previous page load.\n const path = loc.pathname.replace(/\\/+$/, '')\n if (path.endsWith(RESET_PATH)) return { kind: 'recovery' }\n\n return null\n}\n\n/** Strip auth leftovers from the address bar once the flow is finished, so a\n * reload does not put the user back on the set-password screen (and so the\n * hash router gets a clean slate). */\nexport function clearAuthUrlTokens(): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n url.searchParams.delete(AUTH_INTENT_PARAM)\n if (url.hash.includes('=')) url.hash = ''\n window.history.replaceState(window.history.state, '', url.toString())\n}\n\n/** Add the intent marker to a redirect URL. Absolute or relative; existing\n * params are preserved. */\nexport function withAuthIntent(url: string, intent: 'recovery'): string {\n const base = typeof window === 'undefined' ? 'http://localhost' : window.location.origin\n const parsed = new URL(url, base)\n parsed.searchParams.set(AUTH_INTENT_PARAM, intent)\n return /^https?:\\/\\//i.test(url) ? parsed.toString() : `${parsed.pathname}${parsed.search}${parsed.hash}`\n}\n\n// ---------------------------------------------------------------------------\n// Whether the user owes us a password before they reach the app. Pure, so the\n// decision is testable without a browser; the React wrapper lives in\n// @fayz-ai/plugin-auth (usePasswordSetupGate).\n// ---------------------------------------------------------------------------\n\nexport type PasswordSetupReason = 'recovery' | 'invite'\n\nexport interface PasswordSetupInput {\n intent: AuthUrlIntent | null\n /** Session still resolving — the link's tokens are exchanged asynchronously. */\n isLoading: boolean\n isAuthenticated: boolean\n /** AuthUser.mustSetPassword — an invitee who never chose one. */\n mustSetPassword?: boolean\n}\n\nexport interface PasswordSetupDecision {\n reason: PasswordSetupReason | null\n expired: boolean\n checking: boolean\n}\n\nconst NOTHING: PasswordSetupDecision = { reason: null, expired: false, checking: false }\n\nexport function decidePasswordSetup(input: PasswordSetupInput): PasswordSetupDecision {\n const { intent, isLoading, isAuthenticated, mustSetPassword } = input\n\n if (intent?.kind === 'expired') return { reason: 'recovery', expired: true, checking: false }\n\n if (intent?.kind === 'recovery') {\n if (isLoading) return { reason: 'recovery', expired: false, checking: true }\n // A recovery link with no session behind it was already used or has expired.\n return { reason: 'recovery', expired: !isAuthenticated, checking: false }\n }\n\n if (!isLoading && isAuthenticated && mustSetPassword) {\n return { reason: 'invite', expired: false, checking: false }\n }\n\n return NOTHING\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js'\nimport type { AuthAdapter, AuthUser, AuthSession, AuthProvider } from '@fayz-ai/core'\nimport { withAuthIntent } from '../lib/url-intent'\n\n/** Metadata flag stamped on invited users (created by a magic link, so they have\n * no password yet) and cleared the moment they choose one. Metadata, not a URL\n * param: it survives the link being opened later, in another browser, or twice —\n * and it needs no new entry in Supabase's redirect allow-list. */\nexport const MUST_SET_PASSWORD_FLAG = 'fayz_must_set_password'\n\nexport interface SupabaseAuthConfig {\n supabaseUrl: string\n supabaseAnonKey: string\n supabaseClient?: SupabaseClient\n callbackUrl?: string\n resetPasswordUrl?: string\n}\n\nfunction mapSupabaseUser(supabaseUser: {\n id: string\n email?: string | null\n created_at?: string\n updated_at?: string | null\n email_confirmed_at?: string | null\n user_metadata?: Record<string, unknown>\n app_metadata?: { providers?: string[]; provider?: string }\n}): AuthUser {\n return {\n id: supabaseUser.id,\n email: supabaseUser.email ?? '',\n fullName:\n (supabaseUser.user_metadata?.['full_name'] as string | undefined) ??\n (supabaseUser.user_metadata?.['name'] as string | undefined) ??\n '',\n avatarUrl: supabaseUser.user_metadata?.['avatar_url'] as string | undefined,\n mustSetPassword: supabaseUser.user_metadata?.[MUST_SET_PASSWORD_FLAG] === true,\n }\n}\n\nfunction mapSupabaseSession(session: {\n access_token: string\n refresh_token?: string\n expires_at?: number\n expires_in?: number\n user: Parameters<typeof mapSupabaseUser>[0]\n}): AuthSession {\n return {\n accessToken: session.access_token,\n refreshToken: session.refresh_token,\n expiresAt:\n session.expires_at ??\n Math.floor(Date.now() / 1000) + (session.expires_in ?? 3600),\n user: mapSupabaseUser(session.user),\n }\n}\n\nexport function createSupabaseAuthAdapter(config: SupabaseAuthConfig): AuthAdapter {\n const supabase = config.supabaseClient ?? createClient(config.supabaseUrl, config.supabaseAnonKey)\n\n return {\n async getSession() {\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (!session) return null\n const mapped = mapSupabaseSession(session)\n return { user: mapped.user, session: mapped }\n },\n\n onAuthStateChange(cb) {\n const {\n data: { subscription },\n } = supabase.auth.onAuthStateChange((_event, session) => {\n cb(session ? mapSupabaseUser(session.user) : null)\n })\n return () => subscription.unsubscribe()\n },\n\n async signIn(email, password) {\n const { data, error } = await supabase.auth.signInWithPassword({ email, password })\n if (error) throw error\n return mapSupabaseSession(data.session)\n },\n\n async signUp(email, password, fullName) {\n const { data, error } = await supabase.auth.signUp({\n email,\n password,\n options: { data: { full_name: fullName } },\n })\n if (error) throw error\n\n // When email confirmation is required, session is null\n if (!data.session) {\n if (!data.user) throw new Error('Signup failed: no user returned')\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n }\n\n return mapSupabaseSession(data.session)\n },\n\n async resendConfirmation(email: string, options?: { redirectTo?: string }) {\n const { error } = await supabase.auth.resend({\n type: 'signup',\n email,\n options: {\n emailRedirectTo:\n options?.redirectTo ??\n config.callbackUrl ??\n (typeof window !== 'undefined' ? window.location.origin : undefined),\n },\n })\n if (error) throw error\n },\n\n async signOut() {\n const { error } = await supabase.auth.signOut()\n if (error) throw error\n },\n\n async signInWithOAuth(provider: AuthProvider) {\n const { error } = await supabase.auth.signInWithOAuth({\n provider: provider as 'google' | 'github' | 'apple',\n options: {\n redirectTo:\n config.callbackUrl ??\n (typeof window !== 'undefined' ? `${window.location.origin}/auth/callback` : undefined),\n },\n })\n if (error) throw error\n },\n\n async resetPassword(email, options) {\n // Root, not `/auth/reset-password`: the shell recognises a recovery link by\n // the link's own `type=recovery` param, so the flow needs no route of its\n // own — and the app root is the one URL every deployment already serves and\n // every Supabase project already allow-lists (a URL outside the allow-list\n // is silently swapped for the project's Site URL, i.e. another app).\n // A host that DOES point recovery somewhere else gets the explicit intent\n // marker, since we cannot assume its landing page carries the params.\n const explicit = options?.redirectTo ?? config.resetPasswordUrl\n const { error } = await supabase.auth.resetPasswordForEmail(email, {\n redirectTo: explicit\n ? withAuthIntent(explicit, 'recovery')\n : typeof window !== 'undefined'\n ? `${window.location.origin}/`\n : undefined,\n })\n if (error) throw error\n },\n\n async updatePassword(password) {\n // Clearing the flag in the same call as the password: one round-trip, and\n // no window where the password is set but the screen still demands one.\n const { data, error } = await supabase.auth.updateUser({\n password,\n data: { [MUST_SET_PASSWORD_FLAG]: false },\n })\n if (error) throw error\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (session) return mapSupabaseSession(session)\n if (!data.user) return undefined\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n },\n\n async handleCallback(url) {\n const target = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n const parsed = new URL(target)\n // The fragment carries the params on the implicit flow; the query on PKCE\n // and on `{{ .TokenHash }}`-style e-mail templates.\n const fragment = new URLSearchParams(parsed.hash.replace(/^#/, ''))\n const param = (key: string) => parsed.searchParams.get(key) ?? fragment.get(key)\n\n const code = param('code')\n if (code) {\n const { data, error } = await supabase.auth.exchangeCodeForSession(code)\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n // Templates that link straight at the app with a token instead of routing\n // through GoTrue's /verify never produce a session on their own.\n const tokenHash = param('token_hash') ?? param('token')\n const type = param('type')\n if (tokenHash && type) {\n const { data, error } = await supabase.auth.verifyOtp({\n token_hash: tokenHash,\n type: type as 'recovery' | 'invite' | 'magiclink' | 'signup' | 'email',\n })\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n const {\n data: { session },\n } = await supabase.auth.getSession()\n return session ? mapSupabaseSession(session) : null\n },\n\n async inviteUser(email, options) {\n // Native, edge-function-free invite: a passwordless magic link. Sends the\n // e-mail + creates the auth user (anon-callable, no service-role/admin).\n // Membership is NOT granted from `data` (a client could forge it) — the\n // accept-time trigger trusts the RLS-protected public.invitations row.\n const { error } = await supabase.auth.signInWithOtp({\n email,\n options: {\n shouldCreateUser: true,\n emailRedirectTo:\n options?.redirectTo ??\n (typeof window !== 'undefined' ? `${window.location.origin}/` : undefined),\n // `data` only lands on users the OTP actually creates, which is exactly\n // who needs a password: the shell holds them on the set-password screen\n // until they choose one, so they can sign in normally from then on.\n data: { ...options?.data, [MUST_SET_PASSWORD_FLAG]: true },\n },\n })\n if (error) throw error\n },\n }\n}\n","import type { AuthAdapter, AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface MockUser {\n id: string\n email: string\n fullName: string\n role?: string\n}\n\nconst DEFAULT_MOCK_USER: MockUser = {\n id: 'mock-user-id',\n email: 'demo@fayz.dev',\n fullName: 'Demo User',\n role: 'admin',\n}\n\nconst STORAGE_KEY = 'fayz:mock-auth'\n\nfunction toAuthUser(mockUser: MockUser): AuthUser {\n return {\n id: mockUser.id,\n email: mockUser.email,\n fullName: mockUser.fullName,\n }\n}\n\nfunction createMockSession(user: AuthUser): AuthSession {\n return {\n accessToken: `mock-token-${user.id}`,\n refreshToken: `mock-refresh-${user.id}`,\n expiresAt: Math.floor(Date.now() / 1000) + 3600,\n user,\n }\n}\n\nfunction getStored(): { user: AuthUser; session: AuthSession } | null {\n try {\n if (typeof localStorage === 'undefined') return null\n const raw = localStorage.getItem(STORAGE_KEY)\n if (!raw) return null\n return JSON.parse(raw) as { user: AuthUser; session: AuthSession }\n } catch {\n return null\n }\n}\n\nfunction setStored(data: { user: AuthUser; session: AuthSession } | null): void {\n try {\n if (typeof localStorage === 'undefined') return\n if (data) {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data))\n } else {\n localStorage.removeItem(STORAGE_KEY)\n }\n } catch {\n // SSR or storage unavailable — silently skip\n }\n}\n\nexport function createMockAuthAdapter(mockUser: MockUser = DEFAULT_MOCK_USER): AuthAdapter {\n const listeners = new Set<(user: AuthUser | null) => void>()\n\n function notifyListeners(user: AuthUser | null): void {\n for (const cb of listeners) cb(user)\n }\n\n return {\n async getSession() {\n return getStored()\n },\n\n onAuthStateChange(cb) {\n listeners.add(cb)\n return () => {\n listeners.delete(cb)\n }\n },\n\n async signIn(email, _password) {\n // Mock accepts any credentials, but the identity FOLLOWS the email —\n // storefront customers and saas users keep their own purchase/session\n // history instead of all becoming the configured demo user.\n const stored = getStored()\n const user: AuthUser =\n stored && stored.user.email === email\n ? stored.user\n : {\n id: email === mockUser.email ? mockUser.id : `mock-${email}`,\n email,\n fullName: email === mockUser.email ? mockUser.fullName : (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signUp(email, _password, fullName) {\n // Mock signup creates a user from the provided details\n const user: AuthUser = {\n id: `mock-${email}`,\n email,\n fullName: fullName || (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signOut() {\n setStored(null)\n notifyListeners(null)\n },\n\n async signInWithOAuth(_provider) {\n // Mock OAuth signs in as the configured user\n const user = toAuthUser(mockUser)\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n },\n\n async resetPassword(_email) {\n // No-op in mock\n },\n\n async updatePassword(_password) {\n const stored = getStored()\n return stored?.session\n },\n\n async handleCallback() {\n return getStored()?.session ?? null\n },\n\n async inviteUser(_email, _options) {\n // No admin path in mock — the org mock adapter still records the pending\n // invite so the Team UI shows it. Delivery is a no-op locally.\n },\n }\n}\n","import { create } from 'zustand'\nimport type { AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface AuthState {\n user: AuthUser | null\n session: AuthSession | null\n isLoading: boolean\n isAuthenticated: boolean\n error: Error | null\n /**\n * Set when a sign-up succeeded but the account cannot be used until the\n * address is confirmed. Deliberately NOT a session: an account in this state\n * has no access token, and treating it as signed in is what used to let\n * someone into the app where every request came back 401.\n */\n pendingVerification: { email: string } | null\n}\n\nexport interface AuthStore extends AuthState {\n setUser: (user: AuthUser | null) => void\n setSession: (session: AuthSession | null) => void\n setLoading: (isLoading: boolean) => void\n setError: (error: Error | null) => void\n setPendingVerification: (pending: { email: string } | null) => void\n reset: () => void\n}\n\nconst initialState: AuthState = {\n user: null,\n session: null,\n isLoading: true,\n isAuthenticated: false,\n error: null,\n pendingVerification: null,\n}\n\nexport const useAuthStore = create<AuthStore>((set) => ({\n ...initialState,\n\n setUser: (user) =>\n set({ user, isAuthenticated: user !== null }),\n\n setSession: (session) =>\n set({\n session,\n user: session?.user ?? null,\n isAuthenticated: session !== null,\n // A real session arriving is the confirmation landing — the notice it\n // would otherwise keep showing is now about an address already verified.\n ...(session ? { pendingVerification: null } : {}),\n }),\n\n setLoading: (isLoading) => set({ isLoading }),\n\n setError: (error) => set({ error }),\n\n setPendingVerification: (pendingVerification) => set({ pendingVerification }),\n\n reset: () => set(initialState),\n}))\n","import React, { createContext, useContext, useEffect, useRef } from 'react'\nimport type { AuthAdapter, AuthProvider as OAuthProvider, AuthSession } from '@fayz-ai/core'\nimport { useAuthStore } from './store'\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\ninterface AuthContextValue {\n signIn: (email: string, password: string) => Promise<AuthSession>\n signUp: (email: string, password: string, fullName: string) => Promise<AuthSession>\n signOut: () => Promise<void>\n signInWithOAuth: (provider: OAuthProvider) => Promise<void>\n resetPassword: (email: string, options?: { redirectTo?: string }) => Promise<void>\n updatePassword: (password: string) => Promise<AuthSession | void>\n handleCallback: (url?: string) => Promise<AuthSession | null>\n inviteUser: (email: string, options?: { redirectTo?: string; data?: Record<string, unknown> }) => Promise<void>\n /** Re-send the sign-up confirmation. Resolves `false` when the adapter has no such path. */\n resendConfirmation: (email: string, options?: { redirectTo?: string }) => Promise<boolean>\n /** Abandon the pending sign-up so the login screen goes back to its form. */\n clearPendingVerification: () => void\n}\n\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface AuthProviderProps {\n adapter: AuthAdapter\n children: React.ReactNode\n}\n\nexport function AuthProvider({ adapter, children }: AuthProviderProps) {\n const { setSession, setLoading, setError, setPendingVerification, reset } = useAuthStore()\n\n // Keep a stable ref to the adapter so the effect only runs once on mount\n const adapterRef = useRef(adapter)\n adapterRef.current = adapter\n\n useEffect(() => {\n let unsubscribe: (() => void) | undefined\n\n async function init() {\n try {\n setLoading(true)\n const result = await adapterRef.current.getSession()\n setSession(result?.session ?? null)\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)))\n } finally {\n setLoading(false)\n }\n\n // Subscribe to future auth state changes\n unsubscribe = adapterRef.current.onAuthStateChange((user) => {\n if (!user) {\n reset()\n // Keep isLoading false after an explicit sign-out\n setLoading(false)\n return\n }\n // Positive change (adapter-driven sign-in — e.g. an external callback,\n // another tab, or a direct adapter.signUp bridge) — sync the session so\n // consumers reflect it even when the call didn't go through ctx.signIn.\n void adapterRef.current.getSession().then((result) => setSession(result?.session ?? null)).catch(() => {})\n })\n }\n\n void init()\n\n return () => {\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const value: AuthContextValue = {\n async signIn(email, password) {\n setError(null)\n try {\n const session = await adapterRef.current.signIn(email, password)\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signUp(email, password, fullName) {\n setError(null)\n try {\n const session = await adapterRef.current.signUp(email, password, fullName)\n // A project with \"confirm email\" on returns a session with no access\n // token — the account exists but cannot do anything yet. Storing it as\n // a session marked the user authenticated, the AuthGate waved them into\n // the app, and every request 401'd. Park it as pending instead.\n if (!session.accessToken) {\n setPendingVerification({ email })\n return session\n }\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signOut() {\n setError(null)\n try {\n await adapterRef.current.signOut()\n reset()\n setLoading(false)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signInWithOAuth(provider) {\n setError(null)\n try {\n await adapterRef.current.signInWithOAuth(provider)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async resetPassword(email, options) {\n setError(null)\n try {\n await adapterRef.current.resetPassword(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async updatePassword(password) {\n setError(null)\n try {\n const session = await adapterRef.current.updatePassword?.(password)\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async handleCallback(url) {\n setError(null)\n try {\n const session = await adapterRef.current.handleCallback?.(url) ?? null\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async inviteUser(email, options) {\n setError(null)\n try {\n await adapterRef.current.inviteUser?.(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async resendConfirmation(email, options) {\n setError(null)\n if (!adapterRef.current.resendConfirmation) return false\n try {\n await adapterRef.current.resendConfirmation(email, options)\n return true\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n clearPendingVerification() {\n setPendingVerification(null)\n setError(null)\n },\n }\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useAuth() {\n const ctx = useContext(AuthContext)\n if (!ctx) {\n throw new Error('useAuth must be used inside <AuthProvider>')\n }\n\n const { user, session, isLoading, isAuthenticated, error, pendingVerification } = useAuthStore()\n\n return {\n user,\n session,\n isLoading,\n isAuthenticated,\n error,\n pendingVerification,\n signIn: ctx.signIn,\n signUp: ctx.signUp,\n signOut: ctx.signOut,\n signInWithOAuth: ctx.signInWithOAuth,\n resetPassword: ctx.resetPassword,\n updatePassword: ctx.updatePassword,\n handleCallback: ctx.handleCallback,\n inviteUser: ctx.inviteUser,\n resendConfirmation: ctx.resendConfirmation,\n clearPendingVerification: ctx.clearPendingVerification,\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/lib/url-intent.ts","../src/adapters/supabase.ts","../src/adapters/mock.ts","../src/store.ts","../src/context.tsx"],"names":[],"mappings":";;;;;;;;AA2BO,IAAM,iBAAA,GAAoB;AAIjC,IAAM,UAAA,GAAa,sBAAA;AAQnB,SAAS,QAAA,GAA+B;AAMtC,EAAA,MAAM,GAAA,GAAM,OAAO,MAAA,KAAW,WAAA,GAAc,SAAY,MAAA,CAAO,QAAA;AAC/D,EAAA,IAAI,CAAC,KAAK,OAAO,IAAA;AACjB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,IAAI,QAAA,IAAY,EAAA;AAAA,IAC1B,MAAA,EAAQ,IAAI,MAAA,IAAU,EAAA;AAAA,IACtB,IAAA,EAAM,IAAI,IAAA,IAAQ;AAAA,GACpB;AACF;AAGA,IAAM,aAAiC,QAAA,EAAS;AAIhD,SAAS,WAAW,IAAA,EAA+B;AACjD,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,EAAE,CAAA;AACjC,EAAA,IAAI,CAAC,OAAO,CAAC,GAAA,CA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AAE/F,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,OAAA;AAAA,IACA,SAAA;AAAA,IACA,eAAA;AAAA,IACA,KAAA;AAAA,IACA,mBAAA;AAAA,IACA,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,iBAAiB,GAAA,CAAI,eAAA;AAAA,IACrB,eAAe,GAAA,CAAI,aAAA;AAAA,IACnB,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,YAAY,GAAA,CAAI,UAAA;AAAA,IAChB,oBAAoB,GAAA,CAAI,kBAAA;AAAA,IACxB,0BAA0B,GAAA,CAAI;AAAA,GAChC;AACF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Auth link intent — what the URL the user just arrived on is asking for.\n//\n// A Supabase recovery / magic link lands on the app with the tokens in the URL\n// FRAGMENT (implicit flow is the supabase-js default), e.g.\n//\n// https://app.example.com/#access_token=…&refresh_token=…&type=recovery\n//\n// GoTrue then consumes that fragment and wipes it (`window.location.hash = ''`)\n// as soon as the client initialises — so by the time React renders, the reason\n// the user is here is gone. Hence the module-load snapshot: this file is\n// imported long before any createClient() call, so it always sees the original\n// URL.\n//\n// Errors arrive the same way, without a `type`:\n//\n// https://app.example.com/#error=access_denied&error_code=otp_expired&…\n// ---------------------------------------------------------------------------\n\nexport type AuthUrlIntent =\n /** A password-recovery link — the user must choose a new password now. */\n | { kind: 'recovery' }\n /** A one-time link that was already used or has expired. */\n | { kind: 'expired'; message?: string }\n\n/** Query param apps can put on their own redirect URLs to force the\n * set-password screen (e.g. when they override `resetPasswordUrl`). */\nexport const AUTH_INTENT_PARAM = 'fayz_auth'\n\n/** Path segment the SDK historically used as the reset-password redirect.\n * Still honoured so apps that configured it keep working. */\nconst RESET_PATH = '/auth/reset-password'\n\ninterface UrlSnapshot {\n pathname: string\n search: string\n hash: string\n}\n\nfunction snapshot(): UrlSnapshot | null {\n // `window` without a `location` is a real environment, not a hypothetical:\n // the SSR shim the manifest derivation runs under defines the global and not\n // the URL. This module is imported at the top of the auth context, so it is\n // evaluated anywhere the context is — including there, where reading\n // `window.location.pathname` threw and took the whole derivation with it.\n const loc = typeof window === 'undefined' ? undefined : window.location\n if (!loc) return null\n return {\n pathname: loc.pathname ?? '',\n search: loc.search ?? '',\n hash: loc.hash ?? '',\n }\n}\n\n/** Taken at import time — before any Supabase client can strip the fragment. */\nconst initialUrl: UrlSnapshot | null = snapshot()\n\n/** The fragment can be either auth params (`access_token=…&type=recovery`) or a\n * hash-router path (`#/dashboard`). Only the former parses into pairs. */\nfunction hashParams(hash: string): URLSearchParams {\n const raw = hash.replace(/^#/, '')\n if (!raw || !raw.includes('=')) return new URLSearchParams()\n return new URLSearchParams(raw)\n}\n\nexport function readAuthUrlIntent(url?: UrlSnapshot | null): AuthUrlIntent | null {\n const loc = url ?? initialUrl\n if (!loc) return null\n\n const query = new URLSearchParams(loc.search)\n const hash = hashParams(loc.hash)\n const param = (key: string) => hash.get(key) ?? query.get(key)\n\n const errorCode = param('error_code') ?? param('error')\n const errorDescription = param('error_description')?.replace(/\\+/g, ' ')\n // A dead one-time link (`error_code=otp_expired`). Deliberately narrow: an\n // OAuth `access_denied` is a different failure and must not land here. GoTrue\n // does not echo `type` on error redirects, so recovery and invite links are\n // indistinguishable at this point — the screen offers a fresh link either way.\n if (errorCode && /otp|expired|link/i.test(`${errorCode} ${errorDescription ?? ''}`)) {\n return { kind: 'expired', message: errorDescription ?? undefined }\n }\n\n const marker = query.get(AUTH_INTENT_PARAM)\n const type = param('type')\n if (type === 'recovery' || marker === 'recovery') return { kind: 'recovery' }\n\n // `/auth/reset-password` with no tokens at all: the user opened the reset URL\n // directly, or the tokens were already consumed by a previous page load.\n const path = loc.pathname.replace(/\\/+$/, '')\n if (path.endsWith(RESET_PATH)) return { kind: 'recovery' }\n\n return null\n}\n\n// ---------------------------------------------------------------------------\n// App handoff — arriving from a sibling application already signed in.\n//\n// The products share one Supabase project now, so the same person is one\n// `auth.users` row across all of them. They do NOT share a session: each app is\n// its own origin, and supabase-js keeps the session in that origin's\n// localStorage. Same account, same database, and still a password prompt — which\n// is the friction the switcher exists to remove.\n//\n// So the switcher carries the session over in the URL FRAGMENT, which is the\n// same channel GoTrue's own magic links use and for the same reason: a fragment\n// is never sent to a server, never reaches an access log, and never lands in a\n// Referer header. The module-load snapshot above is what makes reading it\n// reliable — supabase-js wipes the hash as soon as it initialises.\n//\n// Two things keep this from being a hole, and both are required:\n//\n// • The DESTINATION only adopts a handoff whose tokens actually verify — it\n// calls setSession, so a forged fragment fails at GoTrue, not at us.\n// • The SOURCE only ever writes this fragment to an origin listed in\n// `app.apps.url`. A tile is not a free-form link.\n//\n// The honest alternative is one origin with paths per app (/app/resto,\n// /app/loja), where localStorage is shared and no token travels at all. That is\n// a deployment change, and this is the same result without one.\n// ---------------------------------------------------------------------------\n\n/**\n * Fragment keys carrying a sibling app's session.\n *\n * Two keys and not one packed value: a JWT is `header.payload.signature`, so\n * any separator that looked natural — a dot above all — also occurs inside the\n * access token. Packing them cost an afternoon and produced `Invalid JWT\n * structure` at the far end, which reads like a forged token rather than like a\n * string that was cut in the wrong place. Both keys are required, so a\n * half-copied fragment is still a miss.\n */\nexport const APP_HANDOFF_PARAM = 'handoff'\nexport const APP_HANDOFF_REFRESH_PARAM = 'handoff_r'\n/** Fragment key naming the account to land in, so the arrival is not a guess. */\nexport const APP_HANDOFF_TENANT_PARAM = 'account'\n\nexport interface AppHandoff {\n accessToken: string\n refreshToken: string\n /** Which account the user was looking at. Null means \"whichever you'd pick\". */\n tenantId: string | null\n}\n\n/**\n * The session a sibling app handed over, if this page load is such an arrival.\n *\n * Returns null for every ordinary load, which is the overwhelming majority —\n * so a caller can ask on every boot without paying for it.\n */\nexport function readAppHandoff(url?: UrlSnapshot | null): AppHandoff | null {\n const loc = url ?? initialUrl\n if (!loc) return null\n\n const hash = hashParams(loc.hash)\n const accessToken = hash.get(APP_HANDOFF_PARAM)\n const refreshToken = hash.get(APP_HANDOFF_REFRESH_PARAM)\n if (!accessToken || !refreshToken) return null\n\n return {\n accessToken,\n refreshToken,\n tenantId: hash.get(APP_HANDOFF_TENANT_PARAM) || null,\n }\n}\n\n/** Pack a session into the fragment the destination will read. */\nexport function buildAppHandoffUrl(\n appUrl: string,\n session: { accessToken: string; refreshToken: string },\n tenantId?: string | null,\n): string {\n if (!session.accessToken || !session.refreshToken) return appUrl\n const params = new URLSearchParams()\n params.set(APP_HANDOFF_PARAM, session.accessToken)\n params.set(APP_HANDOFF_REFRESH_PARAM, session.refreshToken)\n if (tenantId) params.set(APP_HANDOFF_TENANT_PARAM, tenantId)\n // The hash is replaced, not appended to: an app URL that already carries a\n // hash-router path would otherwise arrive with both, and neither would parse.\n const base = appUrl.split('#')[0]\n return `${base}#${params.toString()}`\n}\n\n/** Strip auth leftovers from the address bar once the flow is finished, so a\n * reload does not put the user back on the set-password screen (and so the\n * hash router gets a clean slate). */\nexport function clearAuthUrlTokens(): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n url.searchParams.delete(AUTH_INTENT_PARAM)\n if (url.hash.includes('=')) url.hash = ''\n window.history.replaceState(window.history.state, '', url.toString())\n}\n\n/** Add the intent marker to a redirect URL. Absolute or relative; existing\n * params are preserved. */\nexport function withAuthIntent(url: string, intent: 'recovery'): string {\n const base = typeof window === 'undefined' ? 'http://localhost' : window.location.origin\n const parsed = new URL(url, base)\n parsed.searchParams.set(AUTH_INTENT_PARAM, intent)\n return /^https?:\\/\\//i.test(url) ? parsed.toString() : `${parsed.pathname}${parsed.search}${parsed.hash}`\n}\n\n// ---------------------------------------------------------------------------\n// Whether the user owes us a password before they reach the app. Pure, so the\n// decision is testable without a browser; the React wrapper lives in\n// @fayz-ai/plugin-auth (usePasswordSetupGate).\n// ---------------------------------------------------------------------------\n\nexport type PasswordSetupReason = 'recovery' | 'invite'\n\nexport interface PasswordSetupInput {\n intent: AuthUrlIntent | null\n /** Session still resolving — the link's tokens are exchanged asynchronously. */\n isLoading: boolean\n isAuthenticated: boolean\n /** AuthUser.mustSetPassword — an invitee who never chose one. */\n mustSetPassword?: boolean\n}\n\nexport interface PasswordSetupDecision {\n reason: PasswordSetupReason | null\n expired: boolean\n checking: boolean\n}\n\nconst NOTHING: PasswordSetupDecision = { reason: null, expired: false, checking: false }\n\nexport function decidePasswordSetup(input: PasswordSetupInput): PasswordSetupDecision {\n const { intent, isLoading, isAuthenticated, mustSetPassword } = input\n\n if (intent?.kind === 'expired') return { reason: 'recovery', expired: true, checking: false }\n\n if (intent?.kind === 'recovery') {\n if (isLoading) return { reason: 'recovery', expired: false, checking: true }\n // A recovery link with no session behind it was already used or has expired.\n return { reason: 'recovery', expired: !isAuthenticated, checking: false }\n }\n\n if (!isLoading && isAuthenticated && mustSetPassword) {\n return { reason: 'invite', expired: false, checking: false }\n }\n\n return NOTHING\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js'\nimport type { AuthAdapter, AuthUser, AuthSession, AuthProvider } from '@fayz-ai/core'\nimport { withAuthIntent } from '../lib/url-intent'\n\n/** Metadata flag stamped on invited users (created by a magic link, so they have\n * no password yet) and cleared the moment they choose one. Metadata, not a URL\n * param: it survives the link being opened later, in another browser, or twice —\n * and it needs no new entry in Supabase's redirect allow-list. */\nexport const MUST_SET_PASSWORD_FLAG = 'fayz_must_set_password'\n\nexport interface SupabaseAuthConfig {\n supabaseUrl: string\n supabaseAnonKey: string\n supabaseClient?: SupabaseClient\n callbackUrl?: string\n resetPasswordUrl?: string\n}\n\nfunction mapSupabaseUser(supabaseUser: {\n id: string\n email?: string | null\n created_at?: string\n updated_at?: string | null\n email_confirmed_at?: string | null\n user_metadata?: Record<string, unknown>\n app_metadata?: { providers?: string[]; provider?: string }\n}): AuthUser {\n return {\n id: supabaseUser.id,\n email: supabaseUser.email ?? '',\n fullName:\n (supabaseUser.user_metadata?.['full_name'] as string | undefined) ??\n (supabaseUser.user_metadata?.['name'] as string | undefined) ??\n '',\n avatarUrl: supabaseUser.user_metadata?.['avatar_url'] as string | undefined,\n mustSetPassword: supabaseUser.user_metadata?.[MUST_SET_PASSWORD_FLAG] === true,\n }\n}\n\nfunction mapSupabaseSession(session: {\n access_token: string\n refresh_token?: string\n expires_at?: number\n expires_in?: number\n user: Parameters<typeof mapSupabaseUser>[0]\n}): AuthSession {\n return {\n accessToken: session.access_token,\n refreshToken: session.refresh_token,\n expiresAt:\n session.expires_at ??\n Math.floor(Date.now() / 1000) + (session.expires_in ?? 3600),\n user: mapSupabaseUser(session.user),\n }\n}\n\nexport function createSupabaseAuthAdapter(config: SupabaseAuthConfig): AuthAdapter {\n const supabase = config.supabaseClient ?? createClient(config.supabaseUrl, config.supabaseAnonKey)\n\n return {\n async getSession() {\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (!session) return null\n const mapped = mapSupabaseSession(session)\n return { user: mapped.user, session: mapped }\n },\n\n onAuthStateChange(cb) {\n const {\n data: { subscription },\n } = supabase.auth.onAuthStateChange((_event, session) => {\n cb(session ? mapSupabaseUser(session.user) : null)\n })\n return () => subscription.unsubscribe()\n },\n\n async signIn(email, password) {\n const { data, error } = await supabase.auth.signInWithPassword({ email, password })\n if (error) throw error\n return mapSupabaseSession(data.session)\n },\n\n /**\n * Adopt a session handed over by a sibling application (see url-intent).\n *\n * `setSession` is the verification, not a formality: GoTrue validates the\n * tokens and rotates the refresh token, so a forged or replayed fragment\n * fails here rather than being trusted because it looked well-formed.\n */\n async adoptSession(accessToken: string, refreshToken: string) {\n const { data, error } = await supabase.auth.setSession({\n access_token: accessToken,\n refresh_token: refreshToken,\n })\n if (error || !data.session) return null\n return mapSupabaseSession(data.session)\n },\n\n async signUp(email, password, fullName) {\n const { data, error } = await supabase.auth.signUp({\n email,\n password,\n options: { data: { full_name: fullName } },\n })\n if (error) throw error\n\n // When email confirmation is required, session is null\n if (!data.session) {\n if (!data.user) throw new Error('Signup failed: no user returned')\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n }\n\n return mapSupabaseSession(data.session)\n },\n\n async resendConfirmation(email: string, options?: { redirectTo?: string }) {\n const { error } = await supabase.auth.resend({\n type: 'signup',\n email,\n options: {\n emailRedirectTo:\n options?.redirectTo ??\n config.callbackUrl ??\n (typeof window !== 'undefined' ? window.location.origin : undefined),\n },\n })\n if (error) throw error\n },\n\n async signOut() {\n const { error } = await supabase.auth.signOut()\n if (error) throw error\n },\n\n async signInWithOAuth(provider: AuthProvider) {\n const { error } = await supabase.auth.signInWithOAuth({\n provider: provider as 'google' | 'github' | 'apple',\n options: {\n redirectTo:\n config.callbackUrl ??\n (typeof window !== 'undefined' ? `${window.location.origin}/auth/callback` : undefined),\n },\n })\n if (error) throw error\n },\n\n async resetPassword(email, options) {\n // Root, not `/auth/reset-password`: the shell recognises a recovery link by\n // the link's own `type=recovery` param, so the flow needs no route of its\n // own — and the app root is the one URL every deployment already serves and\n // every Supabase project already allow-lists (a URL outside the allow-list\n // is silently swapped for the project's Site URL, i.e. another app).\n // A host that DOES point recovery somewhere else gets the explicit intent\n // marker, since we cannot assume its landing page carries the params.\n const explicit = options?.redirectTo ?? config.resetPasswordUrl\n const { error } = await supabase.auth.resetPasswordForEmail(email, {\n redirectTo: explicit\n ? withAuthIntent(explicit, 'recovery')\n : typeof window !== 'undefined'\n ? `${window.location.origin}/`\n : undefined,\n })\n if (error) throw error\n },\n\n async updatePassword(password) {\n // Clearing the flag in the same call as the password: one round-trip, and\n // no window where the password is set but the screen still demands one.\n const { data, error } = await supabase.auth.updateUser({\n password,\n data: { [MUST_SET_PASSWORD_FLAG]: false },\n })\n if (error) throw error\n const {\n data: { session },\n } = await supabase.auth.getSession()\n if (session) return mapSupabaseSession(session)\n if (!data.user) return undefined\n return {\n accessToken: '',\n refreshToken: '',\n expiresAt: 0,\n user: mapSupabaseUser(data.user),\n }\n },\n\n async handleCallback(url) {\n const target = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n const parsed = new URL(target)\n // The fragment carries the params on the implicit flow; the query on PKCE\n // and on `{{ .TokenHash }}`-style e-mail templates.\n const fragment = new URLSearchParams(parsed.hash.replace(/^#/, ''))\n const param = (key: string) => parsed.searchParams.get(key) ?? fragment.get(key)\n\n const code = param('code')\n if (code) {\n const { data, error } = await supabase.auth.exchangeCodeForSession(code)\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n // Templates that link straight at the app with a token instead of routing\n // through GoTrue's /verify never produce a session on their own.\n const tokenHash = param('token_hash') ?? param('token')\n const type = param('type')\n if (tokenHash && type) {\n const { data, error } = await supabase.auth.verifyOtp({\n token_hash: tokenHash,\n type: type as 'recovery' | 'invite' | 'magiclink' | 'signup' | 'email',\n })\n if (error) throw error\n return data.session ? mapSupabaseSession(data.session) : null\n }\n\n const {\n data: { session },\n } = await supabase.auth.getSession()\n return session ? mapSupabaseSession(session) : null\n },\n\n async inviteUser(email, options) {\n // Native, edge-function-free invite: a passwordless magic link. Sends the\n // e-mail + creates the auth user (anon-callable, no service-role/admin).\n // Membership is NOT granted from `data` (a client could forge it) — the\n // accept-time trigger trusts the RLS-protected public.invitations row.\n const { error } = await supabase.auth.signInWithOtp({\n email,\n options: {\n shouldCreateUser: true,\n emailRedirectTo:\n options?.redirectTo ??\n (typeof window !== 'undefined' ? `${window.location.origin}/` : undefined),\n // `data` only lands on users the OTP actually creates, which is exactly\n // who needs a password: the shell holds them on the set-password screen\n // until they choose one, so they can sign in normally from then on.\n data: { ...options?.data, [MUST_SET_PASSWORD_FLAG]: true },\n },\n })\n if (error) throw error\n },\n }\n}\n","import type { AuthAdapter, AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface MockUser {\n id: string\n email: string\n fullName: string\n role?: string\n}\n\nconst DEFAULT_MOCK_USER: MockUser = {\n id: 'mock-user-id',\n email: 'demo@fayz.dev',\n fullName: 'Demo User',\n role: 'admin',\n}\n\nconst STORAGE_KEY = 'fayz:mock-auth'\n\nfunction toAuthUser(mockUser: MockUser): AuthUser {\n return {\n id: mockUser.id,\n email: mockUser.email,\n fullName: mockUser.fullName,\n }\n}\n\nfunction createMockSession(user: AuthUser): AuthSession {\n return {\n accessToken: `mock-token-${user.id}`,\n refreshToken: `mock-refresh-${user.id}`,\n expiresAt: Math.floor(Date.now() / 1000) + 3600,\n user,\n }\n}\n\nfunction getStored(): { user: AuthUser; session: AuthSession } | null {\n try {\n if (typeof localStorage === 'undefined') return null\n const raw = localStorage.getItem(STORAGE_KEY)\n if (!raw) return null\n return JSON.parse(raw) as { user: AuthUser; session: AuthSession }\n } catch {\n return null\n }\n}\n\nfunction setStored(data: { user: AuthUser; session: AuthSession } | null): void {\n try {\n if (typeof localStorage === 'undefined') return\n if (data) {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data))\n } else {\n localStorage.removeItem(STORAGE_KEY)\n }\n } catch {\n // SSR or storage unavailable — silently skip\n }\n}\n\nexport function createMockAuthAdapter(mockUser: MockUser = DEFAULT_MOCK_USER): AuthAdapter {\n const listeners = new Set<(user: AuthUser | null) => void>()\n\n function notifyListeners(user: AuthUser | null): void {\n for (const cb of listeners) cb(user)\n }\n\n return {\n async getSession() {\n return getStored()\n },\n\n onAuthStateChange(cb) {\n listeners.add(cb)\n return () => {\n listeners.delete(cb)\n }\n },\n\n async signIn(email, _password) {\n // Mock accepts any credentials, but the identity FOLLOWS the email —\n // storefront customers and saas users keep their own purchase/session\n // history instead of all becoming the configured demo user.\n const stored = getStored()\n const user: AuthUser =\n stored && stored.user.email === email\n ? stored.user\n : {\n id: email === mockUser.email ? mockUser.id : `mock-${email}`,\n email,\n fullName: email === mockUser.email ? mockUser.fullName : (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signUp(email, _password, fullName) {\n // Mock signup creates a user from the provided details\n const user: AuthUser = {\n id: `mock-${email}`,\n email,\n fullName: fullName || (email.split('@')[0] ?? 'Cliente'),\n }\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n return session\n },\n\n async signOut() {\n setStored(null)\n notifyListeners(null)\n },\n\n async signInWithOAuth(_provider) {\n // Mock OAuth signs in as the configured user\n const user = toAuthUser(mockUser)\n const session = createMockSession(user)\n setStored({ user, session })\n notifyListeners(user)\n },\n\n async resetPassword(_email) {\n // No-op in mock\n },\n\n async updatePassword(_password) {\n const stored = getStored()\n return stored?.session\n },\n\n async handleCallback() {\n return getStored()?.session ?? null\n },\n\n async inviteUser(_email, _options) {\n // No admin path in mock — the org mock adapter still records the pending\n // invite so the Team UI shows it. Delivery is a no-op locally.\n },\n }\n}\n","import { create } from 'zustand'\nimport type { AuthUser, AuthSession } from '@fayz-ai/core'\n\nexport interface AuthState {\n user: AuthUser | null\n session: AuthSession | null\n isLoading: boolean\n isAuthenticated: boolean\n error: Error | null\n /**\n * Set when a sign-up succeeded but the account cannot be used until the\n * address is confirmed. Deliberately NOT a session: an account in this state\n * has no access token, and treating it as signed in is what used to let\n * someone into the app where every request came back 401.\n */\n pendingVerification: { email: string } | null\n}\n\nexport interface AuthStore extends AuthState {\n setUser: (user: AuthUser | null) => void\n setSession: (session: AuthSession | null) => void\n setLoading: (isLoading: boolean) => void\n setError: (error: Error | null) => void\n setPendingVerification: (pending: { email: string } | null) => void\n reset: () => void\n}\n\nconst initialState: AuthState = {\n user: null,\n session: null,\n isLoading: true,\n isAuthenticated: false,\n error: null,\n pendingVerification: null,\n}\n\nexport const useAuthStore = create<AuthStore>((set) => ({\n ...initialState,\n\n setUser: (user) =>\n set({ user, isAuthenticated: user !== null }),\n\n setSession: (session) =>\n set({\n session,\n user: session?.user ?? null,\n isAuthenticated: session !== null,\n // A real session arriving is the confirmation landing — the notice it\n // would otherwise keep showing is now about an address already verified.\n ...(session ? { pendingVerification: null } : {}),\n }),\n\n setLoading: (isLoading) => set({ isLoading }),\n\n setError: (error) => set({ error }),\n\n setPendingVerification: (pendingVerification) => set({ pendingVerification }),\n\n reset: () => set(initialState),\n}))\n","import React, { createContext, useContext, useEffect, useRef } from 'react'\nimport type { AuthAdapter, AuthProvider as OAuthProvider, AuthSession } from '@fayz-ai/core'\nimport { useAuthStore } from './store'\nimport { readAppHandoff, clearAuthUrlTokens } from './lib/url-intent'\n\n/** Adapters that can adopt a session a sibling app handed over. Optional by\n * design: the mock adapter and any third-party one simply do not have it. */\ninterface HandoffCapableAdapter {\n adoptSession(accessToken: string, refreshToken: string): Promise<AuthSession | null>\n}\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\ninterface AuthContextValue {\n signIn: (email: string, password: string) => Promise<AuthSession>\n signUp: (email: string, password: string, fullName: string) => Promise<AuthSession>\n signOut: () => Promise<void>\n signInWithOAuth: (provider: OAuthProvider) => Promise<void>\n resetPassword: (email: string, options?: { redirectTo?: string }) => Promise<void>\n updatePassword: (password: string) => Promise<AuthSession | void>\n handleCallback: (url?: string) => Promise<AuthSession | null>\n inviteUser: (email: string, options?: { redirectTo?: string; data?: Record<string, unknown> }) => Promise<void>\n /** Re-send the sign-up confirmation. Resolves `false` when the adapter has no such path. */\n resendConfirmation: (email: string, options?: { redirectTo?: string }) => Promise<boolean>\n /** Abandon the pending sign-up so the login screen goes back to its form. */\n clearPendingVerification: () => void\n}\n\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface AuthProviderProps {\n adapter: AuthAdapter\n children: React.ReactNode\n}\n\nexport function AuthProvider({ adapter, children }: AuthProviderProps) {\n const { setSession, setLoading, setError, setPendingVerification, reset } = useAuthStore()\n\n // Keep a stable ref to the adapter so the effect only runs once on mount\n const adapterRef = useRef(adapter)\n adapterRef.current = adapter\n\n useEffect(() => {\n let unsubscribe: (() => void) | undefined\n\n async function init() {\n try {\n setLoading(true)\n\n // Arriving from a sibling app's switcher: adopt the session it handed\n // over BEFORE asking for our own, because this origin has none. Adapters\n // without the capability (mock, tests) simply fall through, and a\n // handoff GoTrue rejects also falls through — to the login screen, which\n // is the correct answer for tokens that do not verify.\n const handoff = readAppHandoff()\n const adopt = (adapterRef.current as Partial<HandoffCapableAdapter>).adoptSession\n let adopted: AuthSession | null = null\n if (handoff && typeof adopt === 'function') {\n adopted = await adopt.call(adapterRef.current, handoff.accessToken, handoff.refreshToken)\n clearAuthUrlTokens()\n }\n\n // Falling through on a failed adoption is deliberate: getSession() then\n // finds nothing and the user meets the login screen, which is the right\n // answer for tokens that did not verify.\n const result = adopted ? { session: adopted } : await adapterRef.current.getSession()\n setSession(result?.session ?? null)\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)))\n } finally {\n setLoading(false)\n }\n\n // Subscribe to future auth state changes\n unsubscribe = adapterRef.current.onAuthStateChange((user) => {\n if (!user) {\n reset()\n // Keep isLoading false after an explicit sign-out\n setLoading(false)\n return\n }\n // Positive change (adapter-driven sign-in — e.g. an external callback,\n // another tab, or a direct adapter.signUp bridge) — sync the session so\n // consumers reflect it even when the call didn't go through ctx.signIn.\n void adapterRef.current.getSession().then((result) => setSession(result?.session ?? null)).catch(() => {})\n })\n }\n\n void init()\n\n return () => {\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const value: AuthContextValue = {\n async signIn(email, password) {\n setError(null)\n try {\n const session = await adapterRef.current.signIn(email, password)\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signUp(email, password, fullName) {\n setError(null)\n try {\n const session = await adapterRef.current.signUp(email, password, fullName)\n // A project with \"confirm email\" on returns a session with no access\n // token — the account exists but cannot do anything yet. Storing it as\n // a session marked the user authenticated, the AuthGate waved them into\n // the app, and every request 401'd. Park it as pending instead.\n if (!session.accessToken) {\n setPendingVerification({ email })\n return session\n }\n setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signOut() {\n setError(null)\n try {\n await adapterRef.current.signOut()\n reset()\n setLoading(false)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async signInWithOAuth(provider) {\n setError(null)\n try {\n await adapterRef.current.signInWithOAuth(provider)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async resetPassword(email, options) {\n setError(null)\n try {\n await adapterRef.current.resetPassword(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async updatePassword(password) {\n setError(null)\n try {\n const session = await adapterRef.current.updatePassword?.(password)\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async handleCallback(url) {\n setError(null)\n try {\n const session = await adapterRef.current.handleCallback?.(url) ?? null\n if (session) setSession(session)\n return session\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async inviteUser(email, options) {\n setError(null)\n try {\n await adapterRef.current.inviteUser?.(email, options)\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n async resendConfirmation(email, options) {\n setError(null)\n if (!adapterRef.current.resendConfirmation) return false\n try {\n await adapterRef.current.resendConfirmation(email, options)\n return true\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n setError(error)\n throw error\n }\n },\n\n clearPendingVerification() {\n setPendingVerification(null)\n setError(null)\n },\n }\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useAuth() {\n const ctx = useContext(AuthContext)\n if (!ctx) {\n throw new Error('useAuth must be used inside <AuthProvider>')\n }\n\n const { user, session, isLoading, isAuthenticated, error, pendingVerification } = useAuthStore()\n\n return {\n user,\n session,\n isLoading,\n isAuthenticated,\n error,\n pendingVerification,\n signIn: ctx.signIn,\n signUp: ctx.signUp,\n signOut: ctx.signOut,\n signInWithOAuth: ctx.signInWithOAuth,\n resetPassword: ctx.resetPassword,\n updatePassword: ctx.updatePassword,\n handleCallback: ctx.handleCallback,\n inviteUser: ctx.inviteUser,\n resendConfirmation: ctx.resendConfirmation,\n clearPendingVerification: ctx.clearPendingVerification,\n }\n}\n"]}
@@ -17,6 +17,38 @@ interface UrlSnapshot {
17
17
  hash: string;
18
18
  }
19
19
  export declare function readAuthUrlIntent(url?: UrlSnapshot | null): AuthUrlIntent | null;
20
+ /**
21
+ * Fragment keys carrying a sibling app's session.
22
+ *
23
+ * Two keys and not one packed value: a JWT is `header.payload.signature`, so
24
+ * any separator that looked natural — a dot above all — also occurs inside the
25
+ * access token. Packing them cost an afternoon and produced `Invalid JWT
26
+ * structure` at the far end, which reads like a forged token rather than like a
27
+ * string that was cut in the wrong place. Both keys are required, so a
28
+ * half-copied fragment is still a miss.
29
+ */
30
+ export declare const APP_HANDOFF_PARAM = "handoff";
31
+ export declare const APP_HANDOFF_REFRESH_PARAM = "handoff_r";
32
+ /** Fragment key naming the account to land in, so the arrival is not a guess. */
33
+ export declare const APP_HANDOFF_TENANT_PARAM = "account";
34
+ export interface AppHandoff {
35
+ accessToken: string;
36
+ refreshToken: string;
37
+ /** Which account the user was looking at. Null means "whichever you'd pick". */
38
+ tenantId: string | null;
39
+ }
40
+ /**
41
+ * The session a sibling app handed over, if this page load is such an arrival.
42
+ *
43
+ * Returns null for every ordinary load, which is the overwhelming majority —
44
+ * so a caller can ask on every boot without paying for it.
45
+ */
46
+ export declare function readAppHandoff(url?: UrlSnapshot | null): AppHandoff | null;
47
+ /** Pack a session into the fragment the destination will read. */
48
+ export declare function buildAppHandoffUrl(appUrl: string, session: {
49
+ accessToken: string;
50
+ refreshToken: string;
51
+ }, tenantId?: string | null): string;
20
52
  /** Strip auth leftovers from the address bar once the flow is finished, so a
21
53
  * reload does not put the user back on the set-password screen (and so the
22
54
  * hash router gets a clean slate). */
@@ -1 +1 @@
1
- {"version":3,"file":"url-intent.d.ts","sourceRoot":"","sources":["../../src/lib/url-intent.ts"],"names":[],"mappings":"AAmBA,MAAM,MAAM,aAAa;AACvB,0EAA0E;AACxE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE;AACtB,4DAA4D;GAC1D;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAEzC;wEACwE;AACxE,eAAO,MAAM,iBAAiB,cAAc,CAAA;AAM5C,UAAU,WAAW;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;CACb;AAsBD,wBAAgB,iBAAiB,CAAC,GAAG,CAAC,EAAE,WAAW,GAAG,IAAI,GAAG,aAAa,GAAG,IAAI,CA4BhF;AAED;;uCAEuC;AACvC,wBAAgB,kBAAkB,IAAI,IAAI,CAMzC;AAED;4BAC4B;AAC5B,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,MAAM,CAKtE;AAQD,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,QAAQ,CAAA;AAEvD,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAA;IAC5B,gFAAgF;IAChF,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,OAAO,CAAA;IACxB,iEAAiE;IACjE,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAA;IAClC,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,EAAE,OAAO,CAAA;CAClB;AAID,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,kBAAkB,GAAG,qBAAqB,CAgBpF"}
1
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,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,MAAM,CAKtE;AAQD,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,QAAQ,CAAA;AAEvD,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAA;IAC5B,gFAAgF;IAChF,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,OAAO,CAAA;IACxB,iEAAiE;IACjE,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAA;IAClC,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,EAAE,OAAO,CAAA;CAClB;AAID,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,kBAAkB,GAAG,qBAAqB,CAgBpF"}
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "fayz": {
4
4
  "status": "beta"
5
5
  },
6
- "version": "0.18.0",
6
+ "version": "0.21.0",
7
7
  "description": "Fayz SDK auth — pluggable authentication adapters with React hooks",
8
8
  "type": "module",
9
9
  "sideEffects": false,
@@ -25,7 +25,7 @@
25
25
  "zustand": "^4.5.0 || ^5.0.0"
26
26
  },
27
27
  "dependencies": {
28
- "@fayz-ai/core": "^0.18.0"
28
+ "@fayz-ai/core": "^0.21.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@supabase/supabase-js": "^2.45.0",