mirror of
https://github.com/stack-auth/stack.git
synced 2026-06-13 21:01:21 +08:00
Some checks failed
all-good: Did all the other checks pass? / all-good (push) Has been cancelled
Ensure Prisma migrations are in sync with the schema / check_prisma_migrations (22.x) (push) Has been cancelled
DB migration compat / Check if migrations changed (push) Has been cancelled
Docker Server Build and Push / Docker Build and Push Server (push) Has been cancelled
Docker Server Build and Run / docker (push) Has been cancelled
Runs E2E API Tests (Local Emulator) / E2E Tests (Local Emulator, Node ${{ matrix.node-version }}) (22.x) (push) Has been cancelled
Runs E2E API Tests / E2E Tests (Node ${{ matrix.node-version }}, Freestyle ${{ matrix.freestyle-mode }}) (mock, 22.x) (push) Has been cancelled
Runs E2E API Tests / E2E Tests (Node ${{ matrix.node-version }}, Freestyle ${{ matrix.freestyle-mode }}) (prod, 22.x) (push) Has been cancelled
Runs E2E API Tests with custom port prefix / build (22.x) (push) Has been cancelled
Runs E2E Fallback Tests / E2E Fallback Tests (Node ${{ matrix.node-version }}) (22.x) (push) Has been cancelled
Lint & build / lint_and_build (24) (push) Has been cancelled
TOC Generator / TOC Generator (push) Has been cancelled
DB migration compat / Back-compat — Current branch migrations with ${{ needs.check-migrations-changed.outputs.base_branch }} branch code (push) Has been cancelled
DB migration compat / Forward-compat — Current branch code with ${{ needs.check-migrations-changed.outputs.base_branch }} branch migrations (push) Has been cancelled
DB migration compat / No migration changes (skipped) (push) Has been cancelled
## Summary **Stacked on [#1475](https://github.com/hexclave/stack-auth/pull/1475)** (`cl/hexclave-pr1`, the invisible compatibility layer). Diff vs that base = the actual PR 2 code. This is **PR 2 of the Stack Auth → Hexclave rebrand: the visible flip**. Old wire identifiers (cookies, request/response headers, Bearer prefix, JWT issuers, MCP tool name) keep working indefinitely via PR 1's dual-accept. This PR flips every user-visible surface — package names taught in docs, SDK class names in code examples, dashboard setup snippets, page titles, error messages, email content, CLI binary, default base URLs, GitHub repo slug, contributor guidance — to the Hexclave brand. See [`RENAME-TO-HEXCLAVE.md`](./RENAME-TO-HEXCLAVE.md) → *"PR 2: Rebrand to Hexclave (visible)"* for the full per-work-area spec. ## What's implemented (per the plan's PR 2 scope) - **SDK base URLs** flipped: `defaultBaseUrl` and `defaultAnalyticsBaseUrl` in [common.ts](packages/template/src/lib/stack-app/apps/implementations/common.ts:127) → `https://api.hexclave.com` / `https://r.hexclave.com`. PR 1's [`getHardcodedFallbackUrls`](packages/stack-shared/src/utils/urls.tsx:199) table now keys on the Hexclave domain. - **Domain inventory sweep** (16 subdomains from the plan): every `api/app/docs/discord/demo/mcp/skill/feedback/test/preview/r/api2/api.staging/idp-jwk-audience/built-with.stack-auth.com` reference in production code, docs-mintlify, examples, READMEs, and contributor guidance flipped to `*.hexclave.com`. Carve-outs: PR 1's intentional JWT issuer dual-accept table in [tokens.tsx](apps/backend/src/lib/tokens.tsx), the legacy `./docs/` folder, the `unified-docs-widget` allowlist (deliberately accepts both during DNS transition), and `url-targets.ts` hosted-component default (baked into existing customer deploys). - **`@deprecated` JSDoc** on every `Stack*` public export ([packages/template/src/lib/stack-app/index.ts](packages/template/src/lib/stack-app/index.ts) + [packages/template/src/index.ts](packages/template/src/index.ts)) — `StackClientApp`, `StackServerApp`, `StackAdminApp` + every constructor/options/JSON type, `StackHandler`, `StackProvider`, `StackTheme`, `useStackApp`, `defineStackConfig`, `StackConfig`. Hexclave\* aliases are now canonical. - **Runtime `console.warn`** ([packages/template/src/internal/deprecation-warning.ts](packages/template/src/internal/deprecation-warning.ts)) — once-per-process when the SDK is loaded from a `@stackframe/*` artifact. Detection uses the existing `STACK_COMPILE_TIME_CLIENT_PACKAGE_VERSION_SENTINEL` (rewritten at build time to e.g. `js @stackframe/stack@2.8.92` or `js @hexclave/next@1.0.0`); `@hexclave/*` mirror artifacts short-circuit the warning. - **Tier 3 data migration**: new idempotent SQL migration [`20260523000000_rename_internal_project_to_hexclave`](apps/backend/prisma/migrations/20260523000000_rename_internal_project_to_hexclave/migration.sql) — updates the internal Project `displayName` 'Stack Dashboard' → 'Hexclave Dashboard' and `description` only if both still hold the pre-rebrand defaults. Operator-renamed projects untouched, missing row no-ops, re-runs are no-ops. [`seed.ts`](apps/backend/prisma/seed.ts:87) default flipped. `getSharedEmailConfig("Stack Auth")` → `("Hexclave")`. - **Tier 4 brand strings** (mechanical sweep, ~340 files): - Page + OpenAPI titles (Hexclave API / Dashboard / REST API / Webhooks API / Documentation). OpenAPI `info.description` documents `X-Hexclave-*` headers as canonical with compat note on `X-Stack-*`. - `HexclaveAssertionError` message text ([errors.tsx:71](packages/stack-shared/src/utils/errors.tsx:71)) — "an error in Stack." → "an error in Hexclave." - Known-error message templates ([known-errors.tsx](packages/stack-shared/src/known-errors.tsx)) flipped to lead with `x-hexclave-*` + the new `docs.hexclave.com` URL; legacy `x-stack-*` mentioned as compat aliases. **25 e2e test files updated in lockstep**. - Email content: failed-emails-digest body, sendTestEmail recipient (now `sent-with-hexclave.com`), test-email-recipient default. - `CHANGELOG.md` title → "Hexclave Changelog". - `AGENTS.md` env var convention: new vars prefix `HEXCLAVE_` / `NEXT_PUBLIC_HEXCLAVE_` for Category A/B; legacy `STACK_*` explicitly noted as accepted via PR 1's dual-read. - **CLI / init wizard**: - Every dashboard setup snippet, init-stack template, and docs-mintlify page teaches `npx @hexclave/cli@latest init` (was `@stackframe/stack-cli`). [setup-page.tsx](apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/(overview)/setup-page.tsx) + [link-existing-onboarding](apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client-parts/link-existing-onboarding.tsx). - [init-stack](packages/init-stack/src/index.ts:634) `STACK_*_INSTALL_PACKAGE_NAME_OVERRIDE` defaults flipped to `@hexclave/*`. - Generated `stack/client.ts` / `stack/server.ts` import from `@hexclave/next` and reference `HexclaveClientApp` / `HexclaveServerApp`. - Internal `StackAuthKeys` dashboard component renamed to `HexclaveKeys`. - **docs-mintlify rewrite** (legacy `./docs/` intentionally untouched per scoping decision): - **78 MDX files swept**. `@stackframe/{react,stack,js,tanstack-start,...}` → `@hexclave/{react,stack,js,...}` in install snippets and code blocks; `Stack*` SDK class names → `Hexclave*` in all code examples; 'Stack Auth' brand phrase → 'Hexclave'. - `openapi/{server,admin,client,webhooks}.json` titles → 'Hexclave REST API' / 'Hexclave Webhooks API'. - **Generators flipped before regeneration**: - [`packages/stack-shared/src/helpers/init-prompt.ts`](packages/stack-shared/src/helpers/init-prompt.ts), [`/ai/prompts.ts`](packages/stack-shared/src/ai/prompts.ts), [`apps/backend/src/lib/ai/prompts.ts`](apps/backend/src/lib/ai/prompts.ts), [`apps/backend/src/lib/ai/tools/create-email-{template,draft}.ts`](apps/backend/src/lib/ai/tools/create-email-template.ts), [`apps/skills/src/app/route.ts`](apps/skills/src/app/route.ts) (taught MCP tool → `ask_hexclave` with compat note; CLI binary teach → `hexclave`), [`docs-mintlify/snippets/home-prompt-island.jsx`](docs-mintlify/snippets/home-prompt-island.jsx), [`packages/template/README.md`](packages/template/README.md) + integrations/convex/component/README.md. - `generate-sdks` propagated changes to `packages/{react,stack,js}`. - **OpenAPI dual-documentation**: [`apps/backend/src/app/api/latest/route.ts`](apps/backend/src/app/api/latest/route.ts) now lists `X-Hexclave-*` headers as primary documented schemas with `X-Stack-*` duplicates marked `.optional()` (both accepted at runtime by PR 1's normalize-at-proxy shim). - **`@stackframe/emails` virtual module**: dual-aliased to `@hexclave/emails` at the bundler boundary ([email-rendering.tsx:89](apps/backend/src/lib/email-rendering.tsx:89)). Stored email templates continue to import from either name; new AI-generated templates and the system prompt teach `@hexclave/emails`. - **Tier 2 mirror-publish wiring** (new this PR, lays the groundwork for `@hexclave/*` first publish): - [`scripts/rewrite-packages-to-hexclave.ts`](scripts/rewrite-packages-to-hexclave.ts) — rewrites 9 publishable `@stackframe/*` → `@hexclave/*` `package.json` files (reads `HEXCLAVE_VERSION` env or `--version=` flag), pins cross-deps to the shared `@hexclave` version, registers `hexclave` bin alongside `stack` for `@hexclave/cli`. - [`.github/workflows/npm-publish.yaml`](.github/workflows/npm-publish.yaml) appended with rewrite-then-republish step. `pnpm publish` skips already-on-npm versions so reruns are safe. - **Sender email domain**: `noreply@stackframe.co` → `noreply@sent-with-hexclave.com` (the dedicated transactional-sender domain split per the plan, to isolate bulk deliverability from `hexclave.com` reputation); `security@` / `team@stack-auth.com` inbound mailboxes → `@hexclave.com`. - **Self-host docs**: docker network / container names in the bash examples flipped from `stack-auth` to `hexclave` (`hexclave-postgres`, `hexclave-clickhouse`, `hexclave.env`). The docker image tag `stackauth/server:latest` stays per the plan's locked decision. - **GitHub repo slug**: `hexclave/stack-auth` → `hexclave/hexclave` in every `package.json` `repository` field, README link, CHANGELOG raw-asset URL. ## Carve-outs (deliberately untouched) - **[`apps/backend/src/lib/tokens.tsx`](apps/backend/src/lib/tokens.tsx)** JWT issuer dual-accept table — PR 1 intentional infrastructure, kept indefinitely. - **Legacy `./docs/` folder** — per scoping decision (only `docs-mintlify/` rewritten). - **`unified-docs-widget` hostname allowlist** — accepts both `.hexclave.com` (canonical) and `.stack-auth.com` (transition window) for DNS rollout. - **`url-targets.ts`** hosted-domain default `.built-with-stack-auth.com` — wire identifier baked into existing customer deploys; indefinite read-fallback. - **Binary visual assets** (logos, favicons, OG images, README screenshots) — out of scope for this PR. Need design work; tracked separately. ## Verification - **`pnpm typecheck`** on `packages/{template,stack-shared,react,stack,js}` + `apps/dashboard`: **all green**. The remaining backend / e-commerce-demo typecheck errors are pre-existing (Prisma codegen output + `./generated/api-versions.json` not present in fresh worktrees without `pnpm run codegen-prisma` + a live DB) and unrelated to this diff. - **`pnpm lint`** on the same 6 packages: all green. - **Final grep** for residual `Stack Auth` / `stack-auth.com` / `@stackframe/stack-cli@latest` references: zero outside the intentional carve-outs above. - **25 e2e test files updated in lockstep** with the known-error message changes (asserted strings flipped to match the new x-hexclave-* + compat-note messages). ## Deploy blockers (ops sequencing before this rebrand goes live) This PR is code-complete, but the rebrand's visible surfaces (SDK default URLs, dashboard links, npm READMEs, REST error messages, runtime deprecation warning) all point at `*.hexclave.com` / `@hexclave/*` resources that don't exist yet. None of these are fixable from a PR — they're ops/registrar/npm work that has to be sequenced before merging this to a release tag. Suggested ordering, hardest blockers first: ### Tier 1 — required before customer-facing deploy (everything below this line *will visibly break customers on day 1* if skipped) 1. **DNS + TLS for `api.hexclave.com` + `api1./api2.hexclave.com`** → must point at the same backend that serves `api.stack-auth.com` (or a backend that mirrors PR 1's dual-accept). The SDK's new `defaultBaseUrl` is `https://api.hexclave.com`; every customer that relied on the old default and upgrades to a post-PR2 SDK build sends API requests here. Until this resolves, every default-config customer's API call NXDOMAINs. 2. **DNS for `app.hexclave.com`** → the dashboard. Referenced in the SDK's default-error messages ("Please create a project on the Hexclave dashboard at https://app.hexclave.com"), the init-stack flow's `wizard-congrats` redirect, and the OAuth dashboard handoff. 3. **DNS for `docs.hexclave.com`** + Mintlify deploy → the SDK runtime deprecation warning (`https://docs.hexclave.com/migration`), every README, every "Learn more" link in the dashboard, and every REST API error body (`/api/overview#authentication`) points here. The MDX is in this PR; the docs build target needs DNS. 4. **DNS for `mcp.hexclave.com`** → the MCP server endpoint that every taught agent integration (`claude mcp add ...`, `cursor`, `codex`, `vscode`) registers. Until this resolves, every `npx @hexclave/cli@latest init` MCP-registration step fails. 5. **Reserve the `@hexclave` npm scope + set repo variable `HEXCLAVE_VERSION`** → the mirror-publish step in `.github/workflows/npm-publish.yaml` is gated on this variable. Without it, the entire taught onboarding command `npx @hexclave/cli@latest init` 404s from the npm registry, *and* every README that says "install `@hexclave/next`" leads to install failure. Pick the initial version intentionally (`1.0.0` or aligned to `@stackframe/stack`); don't accept a silent default. ### Tier 2 — required before announcing the rebrand publicly (lookalike or low-traffic surfaces, but visibly broken) 6. **DNS for `r.hexclave.com`** → the analytics beacon `defaultAnalyticsBaseUrl`. Silent failure if missing (analytics drops), but should land alongside Tier 1. 7. **Register `sent-with-hexclave.com` + full email auth (SPF / DKIM / DMARC)** → the new default sender domain for shared-sender transactional emails. Without it the dashboard "send test email" path emits bounces, and shared-sender flows (`getSharedEmailConfig("Hexclave")`) deliver to spam at best. 8. **MX + SPF / DMARC for `hexclave.com`** → `team@hexclave.com` and `security@hexclave.com` mailboxes. The security disclosure mailbox is referenced in [`.github/SECURITY.md`](.github/SECURITY.md); `team@hexclave.com` is the actual recipient of internal feedback emails sent at runtime by [`apps/backend/src/lib/internal-feedback-emails.tsx`](apps/backend/src/lib/internal-feedback-emails.tsx). Today, every runtime feedback email bounces. 9. **DNS for `skill.hexclave.com`** → the canonical AI-agent skill fetch URL (the agent bootstrap pivot). Without it, the entire "agent downloads `SKILL.md` from a known URL" flow taught in [`packages/stack-shared/src/helpers/init-prompt.ts`](packages/stack-shared/src/helpers/init-prompt.ts) fails. 10. **Create `github.com/hexclave/hexclave` as a public repo** (even as a redirect to `hexclave/stack-auth`) **OR** rewrite every `package.json` `"repository"` field + dashboard footer "view on GitHub" link to point at `hexclave/stack-auth` (which already exists). Currently every npm package page's "Repository" link is dead, and the dashboard's GitHub button + dev-tool repo link are dead. ### Tier 3 — broken but low-visibility / low-traffic 11. **DNS for `discord.hexclave.com`** → Discord invite redirect, used in every README's chip and the dashboard footer. 12. **DNS for `demo.hexclave.com`** → "✨ Demo" badge in every npm package README. Broken-image badge on the package page. 13. **DNS + TLS for `built-with-hexclave.com`** → optional hosted-handler domain (the default reverted to `.built-with-stack-auth.com` in this PR's carve-outs, so this only matters for projects that manually flip). ## Other follow-ups (not deploy-blocking) - **E2E snapshot regen across the full suite** for the dual-emitted `x-hexclave-*` response headers (PR 1 follow-up; `vitest -u` in CI absorbs). - **Binary visual assets** — logos, favicons, OG images, README screenshots; need design pass. - **Backend OpenAPI fumadocs regen** in CI flow — the JSON files in `docs-mintlify/openapi/` are committed but regen runs in CI. Verify the workflow that does this still works against the post-PR2 source. - **Backend typecheck infra debt** — needs `codegen-prisma` + `codegen-route-info` to clear; pre-existing, unaffected by this PR. ## Test plan - [ ] CI runs full e2e suite (with `vitest -u` to absorb residual snapshot deltas, then committed back). - [ ] Spot-check: new `@hexclave/cli init` (once published) generates `hexclave.config.ts` and works against a fresh project. - [ ] Spot-check: existing customer with `@stackframe/stack` import sees the once-per-process `console.warn` recommending `@hexclave/next` on SDK init. - [ ] Manual: dashboard setup page renders the `npx @hexclave/cli@latest init` snippet and the `x-hexclave-publishable-client-key` API header in the curl example. - [ ] Manual: a fresh `pnpm run prisma migrate` against a clean DB sets the internal project displayName to 'Hexclave Dashboard'. --------- Co-authored-by: Konstantin Wohlwend <n2d4xc@gmail.com>
935 lines
37 KiB
Swift
935 lines
37 KiB
Swift
import Foundation
|
|
#if canImport(FoundationNetworking)
|
|
import FoundationNetworking
|
|
#endif
|
|
import Crypto
|
|
#if canImport(AuthenticationServices)
|
|
import AuthenticationServices
|
|
#endif
|
|
|
|
/// OAuth URL result
|
|
public struct OAuthUrlResult: Sendable {
|
|
public let url: URL
|
|
public let state: String
|
|
public let codeVerifier: String
|
|
public let redirectUrl: String
|
|
}
|
|
|
|
/// Get user options
|
|
public enum GetUserOr: Sendable {
|
|
case returnNull
|
|
case redirect
|
|
case `throw`
|
|
case anonymous
|
|
}
|
|
|
|
/// The main Hexclave client
|
|
public actor StackClientApp {
|
|
public let projectId: String
|
|
|
|
let client: APIClient
|
|
private let baseUrl: String
|
|
private let hasDefaultTokenStore: Bool
|
|
|
|
#if canImport(Security)
|
|
public init(
|
|
projectId: String,
|
|
publishableClientKey: String? = nil,
|
|
baseUrl: String = "https://api.hexclave.com",
|
|
tokenStore: TokenStoreInit = .keychain,
|
|
noAutomaticPrefetch: Bool = false
|
|
) {
|
|
self.projectId = projectId
|
|
self.baseUrl = baseUrl
|
|
|
|
let store: any TokenStoreProtocol
|
|
var hasDefault = true
|
|
switch tokenStore {
|
|
case .keychain:
|
|
// Use registry to ensure singleton per projectId
|
|
store = TokenStoreRegistry.shared.getKeychainStore(projectId: projectId)
|
|
case .memory:
|
|
// Use registry to ensure singleton per projectId
|
|
store = TokenStoreRegistry.shared.getMemoryStore(projectId: projectId)
|
|
case .explicit(let accessToken, let refreshToken):
|
|
store = ExplicitTokenStore(accessToken: accessToken, refreshToken: refreshToken)
|
|
case .none:
|
|
store = NullTokenStore()
|
|
hasDefault = false
|
|
case .custom(let customStore):
|
|
store = customStore
|
|
}
|
|
self.hasDefaultTokenStore = hasDefault
|
|
|
|
self.client = APIClient(
|
|
baseUrl: baseUrl,
|
|
projectId: projectId,
|
|
publishableClientKey: publishableClientKey,
|
|
tokenStore: store
|
|
)
|
|
|
|
// Prefetch project info
|
|
if !noAutomaticPrefetch {
|
|
Task {
|
|
_ = try? await self.getProject()
|
|
}
|
|
}
|
|
}
|
|
#else
|
|
public init(
|
|
projectId: String,
|
|
publishableClientKey: String? = nil,
|
|
baseUrl: String = "https://api.hexclave.com",
|
|
tokenStore: TokenStoreInit = .memory,
|
|
noAutomaticPrefetch: Bool = false
|
|
) {
|
|
self.projectId = projectId
|
|
self.baseUrl = baseUrl
|
|
|
|
let store: any TokenStoreProtocol
|
|
var hasDefault = true
|
|
switch tokenStore {
|
|
case .memory:
|
|
// Use registry to ensure singleton per projectId
|
|
store = TokenStoreRegistry.shared.getMemoryStore(projectId: projectId)
|
|
case .explicit(let accessToken, let refreshToken):
|
|
store = ExplicitTokenStore(accessToken: accessToken, refreshToken: refreshToken)
|
|
case .none:
|
|
store = NullTokenStore()
|
|
hasDefault = false
|
|
case .custom(let customStore):
|
|
store = customStore
|
|
}
|
|
self.hasDefaultTokenStore = hasDefault
|
|
|
|
self.client = APIClient(
|
|
baseUrl: baseUrl,
|
|
projectId: projectId,
|
|
publishableClientKey: publishableClientKey,
|
|
tokenStore: store
|
|
)
|
|
|
|
// Prefetch project info
|
|
if !noAutomaticPrefetch {
|
|
Task {
|
|
_ = try? await self.getProject()
|
|
}
|
|
}
|
|
}
|
|
#endif
|
|
|
|
// MARK: - OAuth
|
|
|
|
/// Get the OAuth authorization URL without redirecting.
|
|
/// Both redirectUrl and errorRedirectUrl must be absolute URLs.
|
|
public func getOAuthUrl(
|
|
provider: String,
|
|
redirectUrl: String,
|
|
errorRedirectUrl: String,
|
|
state: String? = nil,
|
|
codeVerifier: String? = nil
|
|
) async throws -> OAuthUrlResult {
|
|
// Validate that URLs are absolute URLs (panic if not - these are programmer errors)
|
|
guard redirectUrl.contains("://") else {
|
|
fatalError("redirectUrl must be an absolute URL (e.g., 'stack-auth-mobile-oauth-url://success')")
|
|
}
|
|
guard errorRedirectUrl.contains("://") else {
|
|
fatalError("errorRedirectUrl must be an absolute URL (e.g., 'stack-auth-mobile-oauth-url://error')")
|
|
}
|
|
|
|
let actualState = state ?? generateRandomString(length: 32)
|
|
let actualCodeVerifier = codeVerifier ?? generateCodeVerifier()
|
|
let codeChallenge = generateCodeChallenge(from: actualCodeVerifier)
|
|
|
|
var components = URLComponents(string: "\(baseUrl)/api/v1/auth/oauth/authorize/\(provider.lowercased())")!
|
|
let publishableKey = await client.getOAuthClientSecret()
|
|
components.queryItems = [
|
|
URLQueryItem(name: "client_id", value: projectId),
|
|
URLQueryItem(name: "client_secret", value: publishableKey),
|
|
URLQueryItem(name: "redirect_uri", value: redirectUrl),
|
|
URLQueryItem(name: "scope", value: "legacy"),
|
|
URLQueryItem(name: "state", value: actualState),
|
|
URLQueryItem(name: "grant_type", value: "authorization_code"),
|
|
URLQueryItem(name: "code_challenge", value: codeChallenge),
|
|
URLQueryItem(name: "code_challenge_method", value: "S256"),
|
|
URLQueryItem(name: "response_type", value: "code"),
|
|
URLQueryItem(name: "type", value: "authenticate"),
|
|
URLQueryItem(name: "error_redirect_uri", value: errorRedirectUrl)
|
|
]
|
|
|
|
// Add access token if user is already logged in
|
|
|
|
if let accessToken = await client.getAccessToken() {
|
|
components.queryItems?.append(URLQueryItem(name: "token", value: accessToken))
|
|
}
|
|
|
|
guard let url = components.url else {
|
|
throw StackAuthError(code: "invalid_url", message: "Failed to construct OAuth URL")
|
|
}
|
|
|
|
return OAuthUrlResult(url: url, state: actualState, codeVerifier: actualCodeVerifier, redirectUrl: redirectUrl)
|
|
}
|
|
|
|
#if canImport(AuthenticationServices) && !os(watchOS)
|
|
/// Sign in with OAuth using ASWebAuthenticationSession (or native Apple Sign In for "apple" provider)
|
|
/// - Parameters:
|
|
/// - provider: The OAuth provider ID (e.g., "google", "github", "apple")
|
|
/// - presentationContextProvider: Context provider for presenting the auth UI
|
|
@MainActor
|
|
public func signInWithOAuth(
|
|
provider: String,
|
|
presentationContextProvider: ASWebAuthenticationPresentationContextProviding? = nil
|
|
) async throws {
|
|
// Use native Apple Sign In for "apple" provider
|
|
if provider == "apple" {
|
|
try await signInWithAppleNative()
|
|
return
|
|
}
|
|
|
|
let callbackScheme = "stack-auth-mobile-oauth-url"
|
|
let oauth = try await getOAuthUrl(
|
|
provider: provider,
|
|
redirectUrl: callbackScheme + "://success",
|
|
errorRedirectUrl: callbackScheme + "://error"
|
|
)
|
|
|
|
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
|
let session = ASWebAuthenticationSession(
|
|
url: oauth.url,
|
|
callbackURLScheme: callbackScheme
|
|
) { callbackUrl, error in
|
|
if let error = error {
|
|
if (error as NSError).code == ASWebAuthenticationSessionError.canceledLogin.rawValue {
|
|
continuation.resume(throwing: StackAuthError(code: "oauth_cancelled", message: "User cancelled OAuth"))
|
|
} else {
|
|
continuation.resume(throwing: OAuthError(code: "oauth_error", message: error.localizedDescription))
|
|
}
|
|
return
|
|
}
|
|
|
|
guard let callbackUrl = callbackUrl else {
|
|
continuation.resume(throwing: OAuthError(code: "oauth_error", message: "No callback URL received"))
|
|
return
|
|
}
|
|
|
|
Task {
|
|
do {
|
|
try await self.callOAuthCallback(url: callbackUrl, codeVerifier: oauth.codeVerifier, redirectUrl: oauth.redirectUrl)
|
|
continuation.resume()
|
|
} catch {
|
|
continuation.resume(throwing: error)
|
|
}
|
|
}
|
|
}
|
|
|
|
session.prefersEphemeralWebBrowserSession = false
|
|
|
|
#if os(iOS) || os(macOS)
|
|
if let provider = presentationContextProvider {
|
|
session.presentationContextProvider = provider
|
|
}
|
|
#endif
|
|
|
|
session.start()
|
|
}
|
|
}
|
|
|
|
/// Native Apple Sign In using ASAuthorizationController
|
|
@MainActor
|
|
private func signInWithAppleNative() async throws {
|
|
let appleIDProvider = ASAuthorizationAppleIDProvider()
|
|
let request = appleIDProvider.createRequest()
|
|
request.requestedScopes = [.fullName, .email]
|
|
|
|
let authController = ASAuthorizationController(authorizationRequests: [request])
|
|
|
|
// Use delegate helper to bridge async/await
|
|
let credential = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<ASAuthorizationAppleIDCredential, Error>) in
|
|
let delegate = AppleSignInDelegate(continuation: continuation)
|
|
authController.delegate = delegate
|
|
|
|
// Keep delegate alive during the authorization
|
|
objc_setAssociatedObject(authController, "delegate", delegate, .OBJC_ASSOCIATION_RETAIN)
|
|
|
|
authController.performRequests()
|
|
}
|
|
|
|
// Extract identity token
|
|
guard let identityTokenData = credential.identityToken,
|
|
let identityToken = String(data: identityTokenData, encoding: .utf8) else {
|
|
throw StackAuthError(code: "oauth_error", message: "No identity token received from Apple")
|
|
}
|
|
|
|
try await exchangeAppleIdentityToken(identityToken)
|
|
}
|
|
|
|
/// Exchange Apple identity token for Hexclave tokens
|
|
private func exchangeAppleIdentityToken(_ identityToken: String) async throws {
|
|
let url = URL(string: "\(baseUrl)/api/v1/auth/oauth/callback/apple/native")!
|
|
var request = URLRequest(url: url)
|
|
request.httpMethod = "POST"
|
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
request.setValue(projectId, forHTTPHeaderField: "x-stack-project-id")
|
|
request.setValue("client", forHTTPHeaderField: "x-stack-access-type")
|
|
|
|
if let publishableKey = await client.publishableClientKey {
|
|
request.setValue(publishableKey, forHTTPHeaderField: "x-stack-publishable-client-key")
|
|
}
|
|
|
|
let body = ["id_token": identityToken]
|
|
request.httpBody = try JSONSerialization.data(withJSONObject: body)
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: request)
|
|
|
|
guard let httpResponse = response as? HTTPURLResponse else {
|
|
throw OAuthError(code: "invalid_response", message: "Invalid HTTP response")
|
|
}
|
|
|
|
if httpResponse.statusCode != 200 {
|
|
// Check for known error in response
|
|
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let errorCode = json["code"] as? String {
|
|
if errorCode == "INVALID_APPLE_CREDENTIALS" {
|
|
fatalError("Invalid Apple credentials")
|
|
}
|
|
let message = json["error"] as? String ?? "Apple Sign In failed"
|
|
throw OAuthError(code: errorCode, message: message)
|
|
}
|
|
throw OAuthError(code: "apple_signin_failed", message: "HTTP \(httpResponse.statusCode)")
|
|
}
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String,
|
|
let refreshToken = json["refresh_token"] as? String else {
|
|
throw OAuthError(code: "parse_error", message: "Failed to parse Apple Sign In response")
|
|
}
|
|
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
#endif
|
|
|
|
/// Complete the OAuth flow with the callback URL
|
|
/// - Parameters:
|
|
/// - url: The callback URL received from the OAuth provider
|
|
/// - codeVerifier: The PKCE code verifier used during authorization
|
|
/// - redirectUrl: The redirect URL used during authorization (must match exactly for token exchange)
|
|
public func callOAuthCallback(url: URL, codeVerifier: String, redirectUrl: String) async throws {
|
|
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
|
|
|
|
guard let code = components?.queryItems?.first(where: { $0.name == "code" })?.value else {
|
|
if let error = components?.queryItems?.first(where: { $0.name == "error" })?.value {
|
|
let description = components?.queryItems?.first(where: { $0.name == "error_description" })?.value ?? "OAuth error"
|
|
throw OAuthError(code: error, message: description)
|
|
}
|
|
throw OAuthError(code: "missing_code", message: "No authorization code in callback URL")
|
|
}
|
|
|
|
// Exchange code for tokens
|
|
let tokenUrl = URL(string: "\(baseUrl)/api/v1/auth/oauth/token")!
|
|
var request = URLRequest(url: tokenUrl)
|
|
request.httpMethod = "POST"
|
|
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
|
request.setValue(projectId, forHTTPHeaderField: "x-stack-project-id")
|
|
|
|
let publishableKey = await client.getOAuthClientSecret()
|
|
let body = [
|
|
"grant_type=authorization_code",
|
|
"code=\(formURLEncode(code))",
|
|
"redirect_uri=\(formURLEncode(redirectUrl))",
|
|
"code_verifier=\(formURLEncode(codeVerifier))",
|
|
"client_id=\(formURLEncode(projectId))",
|
|
"client_secret=\(formURLEncode(publishableKey))"
|
|
].joined(separator: "&")
|
|
|
|
request.httpBody = body.data(using: .utf8)
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: request)
|
|
|
|
guard let httpResponse = response as? HTTPURLResponse else {
|
|
throw OAuthError(code: "invalid_response", message: "Invalid HTTP response")
|
|
}
|
|
|
|
if httpResponse.statusCode != 200 {
|
|
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let errorCode = json["error"] as? String {
|
|
let message = json["error_description"] as? String ?? "Token exchange failed"
|
|
throw OAuthError(code: errorCode, message: message)
|
|
}
|
|
throw OAuthError(code: "token_exchange_failed", message: "HTTP \(httpResponse.statusCode)")
|
|
}
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String else {
|
|
throw OAuthError(code: "parse_error", message: "Failed to parse token response")
|
|
}
|
|
|
|
let refreshToken = json["refresh_token"] as? String
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
|
|
// MARK: - Credential Auth
|
|
|
|
public func signInWithCredential(email: String, password: String) async throws {
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/auth/password/sign-in",
|
|
method: "POST",
|
|
body: ["email": email, "password": password]
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String,
|
|
let refreshToken = json["refresh_token"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse sign-in response")
|
|
}
|
|
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
|
|
public func signUpWithCredential(
|
|
email: String,
|
|
password: String,
|
|
verificationCallbackUrl: String? = nil
|
|
) async throws {
|
|
var body: [String: Any] = ["email": email, "password": password]
|
|
if let callbackUrl = verificationCallbackUrl {
|
|
body["verification_callback_url"] = callbackUrl
|
|
}
|
|
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/auth/password/sign-up",
|
|
method: "POST",
|
|
body: body
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String,
|
|
let refreshToken = json["refresh_token"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse sign-up response")
|
|
}
|
|
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
|
|
// MARK: - Magic Link
|
|
|
|
public func sendMagicLinkEmail(email: String, callbackUrl: String) async throws -> String {
|
|
let body: [String: Any] = [
|
|
"email": email,
|
|
"callback_url": callbackUrl
|
|
]
|
|
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/auth/otp/send-sign-in-code",
|
|
method: "POST",
|
|
body: body
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let nonce = json["nonce"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse magic link response")
|
|
}
|
|
|
|
return nonce
|
|
}
|
|
|
|
public func signInWithMagicLink(code: String) async throws {
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/auth/otp/sign-in",
|
|
method: "POST",
|
|
body: ["code": code]
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String,
|
|
let refreshToken = json["refresh_token"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse magic link sign-in response")
|
|
}
|
|
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
|
|
// MARK: - MFA
|
|
|
|
public func signInWithMfa(totp: String, code: String) async throws {
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/auth/mfa/sign-in",
|
|
method: "POST",
|
|
body: [
|
|
"type": "totp",
|
|
"totp": totp,
|
|
"code": code
|
|
]
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String,
|
|
let refreshToken = json["refresh_token"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse MFA sign-in response")
|
|
}
|
|
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
|
|
// MARK: - Password Reset
|
|
|
|
public func sendForgotPasswordEmail(email: String, callbackUrl: String) async throws {
|
|
let body: [String: Any] = [
|
|
"email": email,
|
|
"callback_url": callbackUrl
|
|
]
|
|
|
|
_ = try await client.sendRequest(
|
|
path: "/auth/password/send-reset-code",
|
|
method: "POST",
|
|
body: body
|
|
)
|
|
}
|
|
|
|
public func resetPassword(code: String, password: String) async throws {
|
|
_ = try await client.sendRequest(
|
|
path: "/auth/password/reset",
|
|
method: "POST",
|
|
body: ["code": code, "password": password]
|
|
)
|
|
}
|
|
|
|
public func verifyPasswordResetCode(_ code: String) async throws {
|
|
_ = try await client.sendRequest(
|
|
path: "/auth/password/reset/check-code",
|
|
method: "POST",
|
|
body: ["code": code]
|
|
)
|
|
}
|
|
|
|
// MARK: - Email Verification
|
|
|
|
public func verifyEmail(code: String) async throws {
|
|
_ = try await client.sendRequest(
|
|
path: "/contact-channels/verify",
|
|
method: "POST",
|
|
body: ["code": code]
|
|
)
|
|
}
|
|
|
|
// MARK: - Team Invitations
|
|
|
|
public func acceptTeamInvitation(code: String, tokenStore: TokenStoreInit? = nil) async throws {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
_ = try await client.sendRequest(
|
|
path: "/team-invitations/accept",
|
|
method: "POST",
|
|
body: ["code": code],
|
|
authenticated: true,
|
|
tokenStoreOverride: overrideStore
|
|
)
|
|
}
|
|
|
|
public func verifyTeamInvitationCode(_ code: String, tokenStore: TokenStoreInit? = nil) async throws {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
_ = try await client.sendRequest(
|
|
path: "/team-invitations/accept/check-code",
|
|
method: "POST",
|
|
body: ["code": code],
|
|
authenticated: true,
|
|
tokenStoreOverride: overrideStore
|
|
)
|
|
}
|
|
|
|
public func getTeamInvitationDetails(code: String, tokenStore: TokenStoreInit? = nil) async throws -> String {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/team-invitations/accept/details",
|
|
method: "POST",
|
|
body: ["code": code],
|
|
authenticated: true,
|
|
tokenStoreOverride: overrideStore
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let teamDisplayName = json["team_display_name"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse team invitation details")
|
|
}
|
|
|
|
return teamDisplayName
|
|
}
|
|
|
|
// MARK: - User
|
|
|
|
public func getUser(or: GetUserOr = .returnNull, includeRestricted: Bool = false, tokenStore: TokenStoreInit? = nil) async throws -> CurrentUser? {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
|
|
// Validate mutually exclusive options
|
|
if or == .anonymous && !includeRestricted {
|
|
throw StackAuthError(
|
|
code: "invalid_options",
|
|
message: "Cannot use { or: 'anonymous' } with { includeRestricted: false }"
|
|
)
|
|
}
|
|
|
|
let includeAnonymous = or == .anonymous
|
|
let effectiveIncludeRestricted = includeRestricted || includeAnonymous
|
|
|
|
// Check if we have tokens
|
|
let hasTokens: Bool
|
|
if let overrideStore = overrideStore {
|
|
hasTokens = await client.getAccessToken(tokenStoreOverride: overrideStore) != nil
|
|
} else {
|
|
hasTokens = await client.getAccessToken() != nil
|
|
}
|
|
|
|
if !hasTokens {
|
|
switch or {
|
|
case .returnNull:
|
|
return nil
|
|
case .redirect:
|
|
throw StackAuthError(code: "redirect_not_supported", message: "Redirects are not supported in Swift SDK")
|
|
case .throw:
|
|
throw UserNotSignedInError()
|
|
case .anonymous:
|
|
try await signUpAnonymously(tokenStoreOverride: overrideStore)
|
|
}
|
|
}
|
|
|
|
do {
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/users/me",
|
|
method: "GET",
|
|
authenticated: true,
|
|
tokenStoreOverride: overrideStore
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
|
return nil
|
|
}
|
|
|
|
let user = CurrentUser(client: client, json: json)
|
|
|
|
// Check if we should return this user
|
|
if await user.isAnonymous && !includeAnonymous {
|
|
return try handleNoUser(or: or)
|
|
}
|
|
|
|
if await user.isRestricted && !effectiveIncludeRestricted {
|
|
return try handleNoUser(or: or)
|
|
}
|
|
|
|
return user
|
|
|
|
} catch {
|
|
return try handleNoUser(or: or)
|
|
}
|
|
}
|
|
|
|
private func handleNoUser(or: GetUserOr) throws -> CurrentUser? {
|
|
switch or {
|
|
case .returnNull, .anonymous:
|
|
return nil
|
|
case .redirect:
|
|
// Can't redirect in Swift
|
|
return nil
|
|
case .throw:
|
|
throw UserNotSignedInError()
|
|
}
|
|
}
|
|
|
|
private func signUpAnonymously(tokenStoreOverride: (any TokenStoreProtocol)? = nil) async throws {
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/auth/anonymous/sign-up",
|
|
method: "POST",
|
|
tokenStoreOverride: tokenStoreOverride
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let accessToken = json["access_token"] as? String,
|
|
let refreshToken = json["refresh_token"] as? String else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse anonymous sign-up response")
|
|
}
|
|
|
|
if let tokenStoreOverride = tokenStoreOverride {
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken, tokenStoreOverride: tokenStoreOverride)
|
|
} else {
|
|
await client.setTokens(accessToken: accessToken, refreshToken: refreshToken)
|
|
}
|
|
}
|
|
|
|
// MARK: - Project
|
|
|
|
public func getProject() async throws -> Project {
|
|
let (data, _) = try await client.sendRequest(
|
|
path: "/projects/current",
|
|
method: "GET"
|
|
)
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
|
throw StackAuthError(code: "parse_error", message: "Failed to parse project response")
|
|
}
|
|
|
|
return Project(from: json)
|
|
}
|
|
|
|
// MARK: - Partial User
|
|
|
|
public func getPartialUser(tokenStore: TokenStoreInit? = nil) async -> TokenPartialUser? {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
|
|
let accessToken: String?
|
|
if let overrideStore = overrideStore {
|
|
accessToken = await client.getAccessToken(tokenStoreOverride: overrideStore)
|
|
} else {
|
|
accessToken = await client.getAccessToken()
|
|
}
|
|
|
|
guard let accessToken = accessToken else {
|
|
return nil
|
|
}
|
|
|
|
// Decode JWT
|
|
let parts = accessToken.split(separator: ".")
|
|
guard parts.count >= 2 else { return nil }
|
|
|
|
var base64 = String(parts[1])
|
|
// Add padding if needed
|
|
while base64.count % 4 != 0 {
|
|
base64 += "="
|
|
}
|
|
// Replace URL-safe characters
|
|
base64 = base64.replacingOccurrences(of: "-", with: "+")
|
|
base64 = base64.replacingOccurrences(of: "_", with: "/")
|
|
|
|
guard let data = Data(base64Encoded: base64),
|
|
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
|
return nil
|
|
}
|
|
|
|
var restrictedReason: User.RestrictedReason? = nil
|
|
if let reason = json["restricted_reason"] as? [String: Any],
|
|
let type = reason["type"] as? String {
|
|
restrictedReason = User.RestrictedReason(type: type)
|
|
}
|
|
|
|
return TokenPartialUser(
|
|
id: json["sub"] as? String ?? "",
|
|
displayName: json["name"] as? String,
|
|
primaryEmail: json["email"] as? String,
|
|
primaryEmailVerified: json["email_verified"] as? Bool ?? false,
|
|
isAnonymous: json["is_anonymous"] as? Bool ?? false,
|
|
isMultiFactorRequired: json["requires_totp_mfa"] as? Bool ?? false,
|
|
isRestricted: json["is_restricted"] as? Bool ?? false,
|
|
restrictedReason: restrictedReason
|
|
)
|
|
}
|
|
|
|
// MARK: - Sign Out
|
|
|
|
public func signOut(tokenStore: TokenStoreInit? = nil) async throws {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
_ = try? await client.sendRequest(
|
|
path: "/auth/sessions/current",
|
|
method: "DELETE",
|
|
authenticated: true,
|
|
tokenStoreOverride: overrideStore
|
|
)
|
|
if let overrideStore = overrideStore {
|
|
await client.clearTokens(tokenStoreOverride: overrideStore)
|
|
} else {
|
|
await client.clearTokens()
|
|
}
|
|
}
|
|
|
|
// MARK: - Tokens
|
|
|
|
public func getAccessToken(tokenStore: TokenStoreInit? = nil) async -> String? {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
if let overrideStore = overrideStore {
|
|
return await client.getAccessToken(tokenStoreOverride: overrideStore)
|
|
}
|
|
return await client.getAccessToken()
|
|
}
|
|
|
|
public func getRefreshToken(tokenStore: TokenStoreInit? = nil) async -> String? {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
if let overrideStore = overrideStore {
|
|
return await client.getRefreshToken(tokenStoreOverride: overrideStore)
|
|
}
|
|
return await client.getRefreshToken()
|
|
}
|
|
|
|
public func getAuthHeaders(tokenStore: TokenStoreInit? = nil) async -> [String: String] {
|
|
let overrideStore = resolveTokenStore(tokenStore)
|
|
let accessToken: String?
|
|
let refreshToken: String?
|
|
|
|
if let overrideStore = overrideStore {
|
|
accessToken = await client.getAccessToken(tokenStoreOverride: overrideStore)
|
|
refreshToken = await client.getRefreshToken(tokenStoreOverride: overrideStore)
|
|
} else {
|
|
accessToken = await client.getAccessToken()
|
|
refreshToken = await client.getRefreshToken()
|
|
}
|
|
|
|
// Build JSON object with only non-nil values
|
|
// JSONSerialization cannot serialize nil, so we must filter them out
|
|
var json: [String: Any] = [:]
|
|
if let accessToken = accessToken {
|
|
json["accessToken"] = accessToken
|
|
}
|
|
if let refreshToken = refreshToken {
|
|
json["refreshToken"] = refreshToken
|
|
}
|
|
|
|
if let data = try? JSONSerialization.data(withJSONObject: json),
|
|
let string = String(data: data, encoding: .utf8) {
|
|
return ["x-stack-auth": string]
|
|
}
|
|
|
|
return ["x-stack-auth": "{}"]
|
|
}
|
|
|
|
// MARK: - Token Store Resolution
|
|
|
|
/// Resolves the effective token store for a function call.
|
|
/// Panics if the constructor's tokenStore was `.none` and no override is provided.
|
|
private func resolveTokenStore(_ override: TokenStoreInit?) -> (any TokenStoreProtocol)? {
|
|
if let override = override {
|
|
return createTokenStoreProtocol(from: override)
|
|
}
|
|
|
|
if !hasDefaultTokenStore {
|
|
fatalError("This StackClientApp was created with tokenStore: .none. You must provide a tokenStore argument for authenticated operations. This is a programmer error.")
|
|
}
|
|
|
|
return nil // Use the default store from client
|
|
}
|
|
|
|
/// Creates a TokenStoreProtocol from a TokenStore enum value.
|
|
/// Uses singleton instances for keychain and memory stores (keyed by projectId)
|
|
/// to ensure shared token storage and refresh locks.
|
|
private func createTokenStoreProtocol(from tokenStore: TokenStoreInit) -> any TokenStoreProtocol {
|
|
switch tokenStore {
|
|
#if canImport(Security)
|
|
case .keychain:
|
|
return TokenStoreRegistry.shared.getKeychainStore(projectId: projectId)
|
|
#endif
|
|
case .memory:
|
|
return TokenStoreRegistry.shared.getMemoryStore(projectId: projectId)
|
|
case .explicit(let accessToken, let refreshToken):
|
|
return ExplicitTokenStore(accessToken: accessToken, refreshToken: refreshToken)
|
|
case .none:
|
|
return NullTokenStore()
|
|
case .custom(let customStore):
|
|
return customStore
|
|
}
|
|
}
|
|
|
|
// MARK: - PKCE Helpers
|
|
|
|
private func generateRandomString(length: Int) -> String {
|
|
let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
return String((0..<length).map { _ in characters.randomElement()! })
|
|
}
|
|
|
|
private func generateCodeVerifier() -> String {
|
|
return generateRandomString(length: 64)
|
|
}
|
|
|
|
private func generateCodeChallenge(from verifier: String) -> String {
|
|
let data = Data(verifier.utf8)
|
|
let hash = SHA256.hash(data: data)
|
|
let base64 = Data(hash).base64EncodedString()
|
|
|
|
// Convert to base64url
|
|
return base64
|
|
.replacingOccurrences(of: "+", with: "-")
|
|
.replacingOccurrences(of: "/", with: "_")
|
|
.replacingOccurrences(of: "=", with: "")
|
|
}
|
|
}
|
|
|
|
// MARK: - Apple Sign In Delegate
|
|
|
|
#if canImport(AuthenticationServices) && !os(watchOS)
|
|
/// Helper class to bridge ASAuthorizationController delegate-based API to async/await
|
|
private class AppleSignInDelegate: NSObject, ASAuthorizationControllerDelegate {
|
|
private let continuation: CheckedContinuation<ASAuthorizationAppleIDCredential, Error>
|
|
|
|
init(continuation: CheckedContinuation<ASAuthorizationAppleIDCredential, Error>) {
|
|
self.continuation = continuation
|
|
}
|
|
|
|
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
|
|
guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {
|
|
continuation.resume(throwing: StackAuthError(code: "oauth_error", message: "Unexpected credential type from Apple"))
|
|
return
|
|
}
|
|
continuation.resume(returning: credential)
|
|
}
|
|
|
|
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
|
|
let nsError = error as NSError
|
|
|
|
// Check if it's an ASAuthorizationError
|
|
if nsError.domain == ASAuthorizationError.errorDomain {
|
|
let errorCode = ASAuthorizationError.Code(rawValue: nsError.code)
|
|
|
|
switch errorCode {
|
|
case .canceled:
|
|
// User tapped Cancel or dismissed the Sign In with Apple dialog
|
|
continuation.resume(throwing: StackAuthError(code: "oauth_cancelled", message: "User cancelled Apple Sign In"))
|
|
|
|
case .unknown:
|
|
// Error 1000 - The app is not properly configured for Sign In with Apple.
|
|
// This is the most common error during development.
|
|
continuation.resume(throwing: StackAuthError(
|
|
code: "apple_signin_not_configured",
|
|
message: "Apple Sign In is not configured correctly (error 1000). " +
|
|
"To fix this: " +
|
|
"(1) Open your project in Xcode, go to Signing & Capabilities, and add 'Sign In with Apple'. " +
|
|
"(2) Ensure the app is signed with a valid Apple Developer certificate (not just a personal team). " +
|
|
"(3) Register your Bundle ID at developer.apple.com and enable Sign In with Apple for it."
|
|
))
|
|
|
|
case .invalidResponse:
|
|
// Apple's servers returned an unexpected/malformed response.
|
|
// Usually a temporary server-side issue.
|
|
continuation.resume(throwing: StackAuthError(
|
|
code: "apple_signin_invalid_response",
|
|
message: "Apple's servers returned an unexpected response. This is usually temporary - please try again in a moment."
|
|
))
|
|
|
|
case .notHandled:
|
|
// No authorization provider could handle this request.
|
|
// This can happen if Apple ID is not set up on the device.
|
|
continuation.resume(throwing: StackAuthError(
|
|
code: "apple_signin_not_handled",
|
|
message: "Apple Sign In could not be completed. Ensure you are signed in to an Apple ID on this device (Settings > Apple ID)."
|
|
))
|
|
|
|
case .failed:
|
|
// Authentication failed - could be network issues, Apple ID issues, etc.
|
|
continuation.resume(throwing: StackAuthError(
|
|
code: "apple_signin_failed",
|
|
message: "Apple Sign In authentication failed. Check your internet connection and ensure your Apple ID is working correctly."
|
|
))
|
|
|
|
case .notInteractive:
|
|
// Attempted silent/automatic sign-in but user interaction is required.
|
|
// This shouldn't happen with our implementation since we always show the dialog.
|
|
continuation.resume(throwing: StackAuthError(
|
|
code: "apple_signin_not_interactive",
|
|
message: "Apple Sign In requires user interaction. Please try signing in again."
|
|
))
|
|
|
|
default:
|
|
continuation.resume(throwing: StackAuthError(
|
|
code: "apple_signin_error",
|
|
message: "Apple Sign In failed with error code \(nsError.code): \(error.localizedDescription)"
|
|
))
|
|
}
|
|
} else {
|
|
// Non-ASAuthorizationError (rare)
|
|
continuation.resume(throwing: OAuthError(code: "oauth_error", message: error.localizedDescription))
|
|
}
|
|
}
|
|
}
|
|
#endif
|