@tangle-network/agent-app 0.60.61 → 0.60.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-auth/index.js +50 -1
- package/dist/app-auth/index.js.map +1 -1
- package/dist/chat-routes/index.js +1 -1
- package/dist/{chunk-TZD35SBQ.js → chunk-7DG6GGRN.js} +14 -7
- package/dist/chunk-7DG6GGRN.js.map +1 -0
- package/dist/sandbox/index.d.ts +4 -0
- package/dist/sandbox/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-TZD35SBQ.js.map +0 -1
package/dist/app-auth/index.js
CHANGED
|
@@ -17,6 +17,44 @@ import { betterAuth } from "better-auth";
|
|
|
17
17
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
18
18
|
var DEFAULT_STATE_COOKIE = "tangle_sso_state";
|
|
19
19
|
var DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60;
|
|
20
|
+
var SESSION_MEMO_MAX_MS = 3e4;
|
|
21
|
+
var SESSION_MEMO_LIMIT = 500;
|
|
22
|
+
var requestSessions = /* @__PURE__ */ new WeakMap();
|
|
23
|
+
var isolateSessions = /* @__PURE__ */ new Map();
|
|
24
|
+
function memoizedSession(scope, ttlMs, request, read) {
|
|
25
|
+
const known = requestSessions.get(request);
|
|
26
|
+
if (known) return known;
|
|
27
|
+
const cookie = request.headers.get("cookie") ?? "";
|
|
28
|
+
const authorization = request.headers.get("authorization") ?? "";
|
|
29
|
+
if (!cookie && !authorization) return read(request);
|
|
30
|
+
const key = `${scope}\0${authorization}\0${cookie}`;
|
|
31
|
+
const now = Date.now();
|
|
32
|
+
const hit = isolateSessions.get(key);
|
|
33
|
+
if (hit && hit.until > now) {
|
|
34
|
+
requestSessions.set(request, hit.session);
|
|
35
|
+
return hit.session;
|
|
36
|
+
}
|
|
37
|
+
const session = read(request).then((value) => {
|
|
38
|
+
const expiresAt = value ? new Date(value.session.expiresAt).getTime() : 0;
|
|
39
|
+
if (!value || !(expiresAt > Date.now())) isolateSessions.delete(key);
|
|
40
|
+
else {
|
|
41
|
+
const entry = isolateSessions.get(key);
|
|
42
|
+
if (entry) entry.until = Math.min(entry.until, expiresAt);
|
|
43
|
+
}
|
|
44
|
+
return value;
|
|
45
|
+
}, (error) => {
|
|
46
|
+
isolateSessions.delete(key);
|
|
47
|
+
throw error;
|
|
48
|
+
});
|
|
49
|
+
isolateSessions.delete(key);
|
|
50
|
+
isolateSessions.set(key, { until: now + ttlMs, session });
|
|
51
|
+
if (isolateSessions.size > SESSION_MEMO_LIMIT) isolateSessions.delete(isolateSessions.keys().next().value);
|
|
52
|
+
requestSessions.set(request, session);
|
|
53
|
+
return session;
|
|
54
|
+
}
|
|
55
|
+
function forgetSessions(scope) {
|
|
56
|
+
for (const key of isolateSessions.keys()) if (key.startsWith(`${scope}\0`)) isolateSessions.delete(key);
|
|
57
|
+
}
|
|
20
58
|
function slugify(name) {
|
|
21
59
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
22
60
|
}
|
|
@@ -155,10 +193,21 @@ function createAppAuth(config) {
|
|
|
155
193
|
advanced: { cookiePrefix, ...config.advanced }
|
|
156
194
|
};
|
|
157
195
|
const auth = betterAuth(options);
|
|
158
|
-
const
|
|
196
|
+
const readSession = async (request) => {
|
|
159
197
|
const session = await auth.api.getSession({ headers: request.headers });
|
|
160
198
|
return session ?? null;
|
|
161
199
|
};
|
|
200
|
+
const memoMs = config.sessionCookieCacheSeconds === false ? 0 : Math.min(SESSION_MEMO_MAX_MS, (config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS) * 1e3);
|
|
201
|
+
const memoScope = `${config.baseURL}\0${cookiePrefix}`;
|
|
202
|
+
const getSession = (request) => memoMs > 0 ? memoizedSession(memoScope, memoMs, request, readSession) : readSession(request);
|
|
203
|
+
const handler = auth.handler;
|
|
204
|
+
auth.handler = async (request) => {
|
|
205
|
+
try {
|
|
206
|
+
return await handler(request);
|
|
207
|
+
} finally {
|
|
208
|
+
if (request.method !== "GET") forgetSessions(memoScope);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
162
211
|
const loginPath = config.loginPath ?? "/login";
|
|
163
212
|
const guard = createAuthGuard({ getSession, loginPath });
|
|
164
213
|
let sso = null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/app-auth/index.ts"],"sourcesContent":["/**\n * better-auth config factory for agent products (#188 Phase 1). Every product\n * hand-rolls the same ~70–150 line setup — drizzle adapter over the standard\n * users/sessions/accounts/verifications tables, email+password with branded\n * reset/verification mail (`./email`), env-gated GitHub/Google social providers, session\n * cookie cache, and a per-app cookie prefix — and tax additionally\n * re-implemented better-auth's cookie signing for its Tangle SSO callback.\n * `createAppAuth` owns that mechanism once and returns the configured\n * better-auth instance plus the request guards products actually use.\n *\n * Domain stays a parameter: the drizzle db + schema, email client, provider\n * credentials, and SSO store/client all come from the product. No product\n * import, no engine re-implementation — the SSO path composes the existing\n * `platform/sso` cookie minter (`createBetterAuthSessionCookieMinter`), which\n * is byte-compatible with better-auth's own `makeSignature` contract.\n *\n * better-auth is an OPTIONAL peer: only this subpath imports it, so it is\n * deliberately NOT re-exported from the root barrel.\n */\n\nimport { betterAuth, type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { noticeEmail, type EmailAttachment, type EmailMessage, type EmailProduct } from '../email'\nimport { createAuthGuard, type AuthGuard } from '../platform/guards'\nimport {\n createBetterAuthSessionCookieMinter,\n createTangleSsoHandlers,\n type TangleSsoAccountStore,\n type TangleSsoAuthClient,\n type TangleSsoHandlers,\n type TangleIdentitySsoAccountStore,\n type TangleIdentitySsoAuthClient,\n type TangleOidcSsoAccountStore,\n type TangleOidcSsoAuthClient,\n} from '../platform/sso'\n\nconst DEFAULT_STATE_COOKIE = 'tangle_sso_state'\nconst DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60\n\n/** Structural slice of a Resend-style client — no `resend` import. */\nexport interface AppAuthEmailClient {\n emails: {\n send(message: {\n from: string\n to: string\n subject: string\n html: string\n text?: string\n /** Inline images the HTML references by `cid:`, such as the Tangle mark. */\n attachments?: EmailAttachment[]\n }): Promise<unknown>\n }\n}\n\n/** Define email configuration for app authentication including client, sender, verification, and warning options */\nexport interface AppAuthEmailConfig {\n /** A Resend-style client, or a lazy getter returning null when the API key\n * is absent (the products' dev default — mail is skipped with a warning,\n * sign-up itself must not crash). */\n resend: AppAuthEmailClient | (() => AppAuthEmailClient | null)\n /** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */\n from: string\n /** Send a verification email on sign-up and auto-sign-in after verifying\n * (the tax/gtm behavior). Default false (the legal behavior). */\n verifyOnSignUp?: boolean\n /** Receives the \"email client unavailable\" warning. Default console.warn. */\n warn?: (message: string) => void\n}\n\n/** Env-shaped: pass the env vars straight through; the provider is registered\n * only when BOTH values are non-empty, so unset env disables it. */\nexport interface AppAuthSocialProviderConfig {\n clientId?: string\n clientSecret?: string\n}\n\n/** Define social authentication configuration options for GitHub and Google providers */\nexport interface AppAuthSocialConfig {\n github?: AppAuthSocialProviderConfig\n google?: AppAuthSocialProviderConfig\n}\n\n/** Cross-site Tangle SSO wiring. The factory supplies the better-auth side —\n * `setSessionCookie` via `createBetterAuthSessionCookieMinter(auth)` (signed\n * `__Secure-`/prefixed cookie that `auth.api.getSession` accepts) — so the\n * product no longer touches `better-auth/crypto` itself. */\nexport interface AppAuthSsoConfig {\n protocol?: 'legacy'\n /** Platform wire client (authorizeUrl + exchange). */\n client: TangleSsoAuthClient\n /** Product persistence: user upsert, session row, platform link. */\n store: TangleSsoAccountStore\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n /** Default 'tangle_sso_state'. */\n stateCookieName?: string\n /** HMAC secret for the CSRF state cookie. Default: the auth `secret`. */\n stateSecret?: string\n /** Default: `baseURL` is https. Must match better-auth's own\n * secure-cookie decision or the cookie name lookup diverges. */\n secureCookies?: boolean\n sessionTtlSeconds?: number\n stateTtlSeconds?: number\n /** Post-login redirect fallback. Default '/app'. */\n defaultRedirectPath?: string\n /** Default: the top-level `loginPath`. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n}\n\n/** Registered OIDC client configuration. The caller supplies Runtime PKCE; login does not mint an API key. */\nexport interface AppAuthOidcSsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'oidc'\n client: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\n/** First-party identity login; no Platform API key is issued or stored. */\nexport interface AppAuthIdentitySsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'identity'\n client: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define the structure for application authentication data including users, sessions, accounts, and verifications */\nexport interface AppAuthSchema {\n users: unknown\n sessions: unknown\n accounts: unknown\n verifications: unknown\n}\n\n/** Define configuration settings for app authentication including app name, base URL, secrets, and trusted origins */\nexport interface AppAuthConfig {\n /** Product name — used in email subjects and as the cookie-prefix default. */\n appName: string\n /** Absolute origin better-auth serves from (`BETTER_AUTH_URL`). */\n baseURL: string\n /** better-auth HMAC secret. Optional only because better-auth falls back to\n * the BETTER_AUTH_SECRET env var; `sso` needs it explicitly (or\n * `sso.stateSecret`). */\n secret?: string\n trustedOrigins?: string[]\n /**\n * Session-cookie prefix. Default: slugified `appName`. A per-app prefix is\n * load-bearing, not cosmetic: the platform (id.tangle.tools) mints its own\n * better-auth cookie `Domain=.tangle.tools`-wide under the DEFAULT name, and\n * the platform's (older) cookie wins the Cookie-header order — an app on the\n * default prefix reads the platform's token, fails its own signature check,\n * and every fresh login lands back on /login.\n */\n cookiePrefix?: string\n /** Drizzle database instance; wired through better-auth's drizzle adapter\n * together with `schema`. */\n db?: unknown\n /** The product's users/sessions/accounts/verifications tables (mapped to\n * better-auth's user/session/account/verification models). */\n schema?: AppAuthSchema\n /** Drizzle dialect. Default 'sqlite' (D1). */\n provider?: 'sqlite' | 'pg' | 'mysql'\n /** Escape hatch: a pre-built better-auth database adapter (e.g.\n * `memoryAdapter` in tests). Wins over `db`/`schema`. */\n database?: BetterAuthOptions['database']\n /** Email+password sign-in. Default true (all current products enable it). */\n emailAndPassword?: boolean\n /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** Session cookie-cache TTL in seconds; `false` disables the cache.\n * Default 300. */\n sessionCookieCacheSeconds?: number | false\n /** Tangle cross-site SSO (start/callback handlers). */\n sso?: AppAuthSsoConfig | AppAuthOidcSsoConfig | AppAuthIdentitySsoConfig\n /** Where guards redirect unauthenticated page requests. Default '/login'. */\n loginPath?: string\n /** Merged over the factory's `advanced` block (cookiePrefix stays unless\n * overridden here). */\n advanced?: BetterAuthOptions['advanced']\n}\n\n/** The configured better-auth instance, typed at better-auth's base surface\n * (`handler`, `api`, `$context`, `$Infer`). */\nexport type AppAuthInstance = Auth\n\n/** What `getSession`/guards resolve: better-auth's base session + user rows. */\nexport interface AppAuthSession {\n session: Session\n user: User\n}\n\n/** Define authentication guard with session retrieval and optional SSO handlers for app requests */\nexport interface AppAuth extends AuthGuard<AppAuthSession> {\n auth: AppAuthInstance\n /** `auth.api.getSession` over a `Request` — the seam the guards consume. */\n getSession(request: Request): Promise<AppAuthSession | null>\n /** Tangle SSO start/callback handlers; null unless `sso` was configured. */\n sso: TangleSsoHandlers | null\n}\n\n/** Lowercased, non-alphanumerics collapsed to '-': `'Legal Agent'` → `'legal-agent'`. */\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction emailProduct(config: AppAuthConfig): EmailProduct {\n return { name: config.appName, url: config.baseURL }\n}\n\nfunction resolveEmailClient(email: AppAuthEmailConfig): AppAuthEmailClient | null {\n return typeof email.resend === 'function' ? email.resend() : email.resend\n}\n\ntype DrizzleAuthAdapter = ReturnType<ReturnType<typeof drizzleAdapter>>\n\n/** Better Auth reads adapter identity during startup, before Workers inject D1.\n * Build the Drizzle adapter on its first database operation. */\nfunction deferDrizzleAdapter(\n db: Record<string, unknown>,\n config: Parameters<typeof drizzleAdapter>[1],\n): ReturnType<typeof drizzleAdapter> {\n return (options) => {\n let adapter: DrizzleAuthAdapter | undefined\n const resolve = () => (adapter ??= drizzleAdapter(db, config)(options))\n\n return {\n id: 'drizzle',\n create: (data) => resolve().create(data),\n findOne: (data) => resolve().findOne(data),\n findMany: (data) => resolve().findMany(data),\n count: (data) => resolve().count(data),\n update: (data) => resolve().update(data),\n updateMany: (data) => resolve().updateMany(data),\n delete: (data) => resolve().delete(data),\n deleteMany: (data) => resolve().deleteMany(data),\n consumeOne: (data) => resolve().consumeOne(data),\n incrementOne: (data) => resolve().incrementOne(data),\n transaction: (callback) => resolve().transaction(callback),\n }\n }\n}\n\n/** Resend reports failures in the resolved value, not by rejecting — surface\n * them loud so better-auth's flow (and the caller's logs) see the failure. */\nasync function sendEmail(client: AppAuthEmailClient, from: string, to: string, message: EmailMessage): Promise<void> {\n const { subject, html, text, attachments } = message\n const result = (await client.emails.send({ from, to, subject, html, text, attachments })) as\n | { error?: { message?: string } | null }\n | null\n | undefined\n if (result && typeof result === 'object' && result.error) {\n throw new Error(`[app-auth] email send failed: ${result.error.message ?? 'unknown error'}`)\n }\n}\n\nfunction resolveDatabase(config: AppAuthConfig): NonNullable<BetterAuthOptions['database']> {\n if (config.database) return config.database\n if (config.db && config.schema) {\n return deferDrizzleAdapter(config.db as Record<string, unknown>, {\n provider: config.provider ?? 'sqlite',\n schema: {\n user: config.schema.users,\n session: config.schema.sessions,\n account: config.schema.accounts,\n verification: config.schema.verifications,\n } as Record<string, unknown>,\n })\n }\n throw new Error(\n 'createAppAuth requires a database: pass `db` + `schema` (drizzle) or `database` (a better-auth adapter)',\n )\n}\n\nfunction resolveSocialProviders(social: AppAuthSocialConfig | undefined): BetterAuthOptions['socialProviders'] {\n const providers: NonNullable<BetterAuthOptions['socialProviders']> = {}\n if (social?.github?.clientId && social.github.clientSecret) {\n providers.github = { clientId: social.github.clientId, clientSecret: social.github.clientSecret }\n }\n if (social?.google?.clientId && social.google.clientSecret) {\n providers.google = { clientId: social.google.clientId, clientSecret: social.google.clientSecret }\n }\n return Object.keys(providers).length > 0 ? providers : undefined\n}\n\nfunction emailAndPasswordOptions(config: AppAuthConfig): BetterAuthOptions['emailAndPassword'] {\n const email = config.email\n if (!email) return { enabled: true }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\n sendResetPassword: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — password reset email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Reset your password',\n title: 'Reset your password',\n body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,\n action: { label: 'Reset password', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: 'You received this because a password reset was requested for this address.' },\n }))\n },\n }\n}\n\nfunction emailVerificationOptions(config: AppAuthConfig): BetterAuthOptions['emailVerification'] {\n const email = config.email\n if (!email?.verifyOnSignUp) return undefined\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n sendOnSignUp: true,\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — verification email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Verify your email',\n title: 'Verify your email',\n body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,\n action: { label: 'Verify email', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` },\n }))\n },\n }\n}\n\n/**\n * Build the product's better-auth instance plus the request-boundary helpers:\n * `getSession` (Request → session|null), the `createAuthGuard` quartet\n * (`requireUser` 302, `requireApiUser` JSON 401, `requireSession`,\n * `getOptionalSession`), and — when `sso` is configured — the Tangle SSO\n * start/callback handlers with the session cookie minted through better-auth's\n * own name/attributes/signing (no `better-auth/crypto` in product code).\n */\nexport function createAppAuth(config: AppAuthConfig): AppAuth {\n if (!config.appName) throw new Error('createAppAuth: appName is required')\n if (!config.baseURL) throw new Error('createAppAuth: baseURL is required')\n\n const cookiePrefix = config.cookiePrefix ?? slugify(config.appName)\n if (!cookiePrefix) throw new Error('createAppAuth: cookiePrefix (or a slugifiable appName) is required')\n\n const socialProviders = resolveSocialProviders(config.social)\n const options: BetterAuthOptions = {\n appName: config.appName,\n baseURL: config.baseURL,\n ...(config.secret ? { secret: config.secret } : {}),\n ...(config.trustedOrigins ? { trustedOrigins: config.trustedOrigins } : {}),\n database: resolveDatabase(config),\n ...(config.emailAndPassword === false ? {} : { emailAndPassword: emailAndPasswordOptions(config) }),\n ...(config.email?.verifyOnSignUp ? { emailVerification: emailVerificationOptions(config) } : {}),\n ...(socialProviders ? { socialProviders } : {}),\n ...(config.sessionCookieCacheSeconds === false\n ? {}\n : {\n session: {\n cookieCache: {\n enabled: true,\n maxAge: config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS,\n },\n },\n }),\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n\n const getSession = async (request: Request): Promise<AppAuthSession | null> => {\n const session = await auth.api.getSession({ headers: request.headers })\n return (session as AppAuthSession | null) ?? null\n }\n\n const loginPath = config.loginPath ?? '/login'\n const guard = createAuthGuard<AppAuthSession>({ getSession, loginPath })\n\n let sso: TangleSsoHandlers | null = null\n if (config.sso) {\n const stateSecret = config.sso.stateSecret ?? config.secret\n if (!stateSecret) {\n throw new Error(\n 'createAppAuth: sso requires `secret` (or sso.stateSecret) — the signed-state CSRF cookie needs an HMAC secret',\n )\n }\n const transport = config.sso.protocol === 'oidc'\n ? { protocol: 'oidc' as const, auth: config.sso.client, store: config.sso.store, createPkcePair: config.sso.createPkcePair }\n : config.sso.protocol === 'identity'\n ? { protocol: 'identity' as const, auth: config.sso.client, store: config.sso.store }\n : { protocol: 'legacy' as const, auth: config.sso.client, store: config.sso.store }\n sso = createTangleSsoHandlers({\n ...transport,\n stateSecret,\n callbackUrl: config.sso.callbackUrl,\n stateCookieName: config.sso.stateCookieName ?? DEFAULT_STATE_COOKIE,\n setSessionCookie: createBetterAuthSessionCookieMinter(auth),\n secureCookies: config.sso.secureCookies ?? config.baseURL.startsWith('https:'),\n ...(config.sso.sessionTtlSeconds !== undefined ? { sessionTtlSeconds: config.sso.sessionTtlSeconds } : {}),\n ...(config.sso.stateTtlSeconds !== undefined ? { stateTtlSeconds: config.sso.stateTtlSeconds } : {}),\n ...(config.sso.defaultRedirectPath ? { defaultRedirectPath: config.sso.defaultRedirectPath } : {}),\n loginPath: config.sso.loginPath ?? loginPath,\n ...(config.sso.log ? { log: config.sso.log } : {}),\n })\n }\n\n return { auth, getSession, ...guard, sso }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,SAAS,kBAA8E;AACvF,SAAS,sBAAsB;AAe/B,IAAM,uBAAuB;AAC7B,IAAM,uCAAuC,IAAI;AAsKjD,SAAS,QAAQ,MAAsB;AACrC,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAC3B;AAEA,SAAS,aAAa,QAAqC;AACzD,SAAO,EAAE,MAAM,OAAO,SAAS,KAAK,OAAO,QAAQ;AACrD;AAEA,SAAS,mBAAmB,OAAsD;AAChF,SAAO,OAAO,MAAM,WAAW,aAAa,MAAM,OAAO,IAAI,MAAM;AACrE;AAMA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AAO,OAAO,IAAI,MAAM;AACpF,UAAM,wBAAwB;AAAA,MAC5B,GAAG;AAAA,MACH;AAAA,MACA,aAAa,OAAO,IAAI;AAAA,MACxB,iBAAiB,OAAO,IAAI,mBAAmB;AAAA,MAC/C,kBAAkB,oCAAoC,IAAI;AAAA,MAC1D,eAAe,OAAO,IAAI,iBAAiB,OAAO,QAAQ,WAAW,QAAQ;AAAA,MAC7E,GAAI,OAAO,IAAI,sBAAsB,SAAY,EAAE,mBAAmB,OAAO,IAAI,kBAAkB,IAAI,CAAC;AAAA,MACxG,GAAI,OAAO,IAAI,oBAAoB,SAAY,EAAE,iBAAiB,OAAO,IAAI,gBAAgB,IAAI,CAAC;AAAA,MAClG,GAAI,OAAO,IAAI,sBAAsB,EAAE,qBAAqB,OAAO,IAAI,oBAAoB,IAAI,CAAC;AAAA,MAChG,WAAW,OAAO,IAAI,aAAa;AAAA,MACnC,GAAI,OAAO,IAAI,MAAM,EAAE,KAAK,OAAO,IAAI,IAAI,IAAI,CAAC;AAAA,IAClD,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,MAAM,YAAY,GAAG,OAAO,IAAI;AAC3C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/app-auth/index.ts"],"sourcesContent":["/**\n * better-auth config factory for agent products (#188 Phase 1). Every product\n * hand-rolls the same ~70–150 line setup — drizzle adapter over the standard\n * users/sessions/accounts/verifications tables, email+password with branded\n * reset/verification mail (`./email`), env-gated GitHub/Google social providers, session\n * cookie cache, and a per-app cookie prefix — and tax additionally\n * re-implemented better-auth's cookie signing for its Tangle SSO callback.\n * `createAppAuth` owns that mechanism once and returns the configured\n * better-auth instance plus the request guards products actually use.\n *\n * Domain stays a parameter: the drizzle db + schema, email client, provider\n * credentials, and SSO store/client all come from the product. No product\n * import, no engine re-implementation — the SSO path composes the existing\n * `platform/sso` cookie minter (`createBetterAuthSessionCookieMinter`), which\n * is byte-compatible with better-auth's own `makeSignature` contract.\n *\n * better-auth is an OPTIONAL peer: only this subpath imports it, so it is\n * deliberately NOT re-exported from the root barrel.\n */\n\nimport { betterAuth, type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { noticeEmail, type EmailAttachment, type EmailMessage, type EmailProduct } from '../email'\nimport { createAuthGuard, type AuthGuard } from '../platform/guards'\nimport {\n createBetterAuthSessionCookieMinter,\n createTangleSsoHandlers,\n type TangleSsoAccountStore,\n type TangleSsoAuthClient,\n type TangleSsoHandlers,\n type TangleIdentitySsoAccountStore,\n type TangleIdentitySsoAuthClient,\n type TangleOidcSsoAccountStore,\n type TangleOidcSsoAuthClient,\n} from '../platform/sso'\n\nconst DEFAULT_STATE_COOKIE = 'tangle_sso_state'\nconst DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60\n\n/**\n * A session read costs two serial database round trips (session, then user),\n * and a request often resolves it more than once. Resolved sessions are reused\n * within a request and, for at most SESSION_MEMO_MAX_MS, across requests in one\n * isolate, keyed by the exact credentials sent. That stays inside the staleness\n * the session cookie cache already accepts, and any non-GET auth call (sign-out,\n * revocation) clears the app's entries in this isolate.\n */\nconst SESSION_MEMO_MAX_MS = 30_000\nconst SESSION_MEMO_LIMIT = 500\nconst requestSessions = new WeakMap<Request, Promise<AppAuthSession | null>>()\nconst isolateSessions = new Map<string, { until: number; session: Promise<AppAuthSession | null> }>()\n\nfunction memoizedSession(scope: string, ttlMs: number, request: Request,\n read: (request: Request) => Promise<AppAuthSession | null>): Promise<AppAuthSession | null> {\n const known = requestSessions.get(request)\n if (known) return known\n const cookie = request.headers.get('cookie') ?? ''\n const authorization = request.headers.get('authorization') ?? ''\n if (!cookie && !authorization) return read(request)\n const key = `${scope}\\u0000${authorization}\\u0000${cookie}`\n const now = Date.now()\n const hit = isolateSessions.get(key)\n if (hit && hit.until > now) {\n requestSessions.set(request, hit.session)\n return hit.session\n }\n const session = read(request).then((value) => {\n // Only a live session is reused; a miss or an expired session is read again next time.\n const expiresAt = value ? new Date(value.session.expiresAt).getTime() : 0\n if (!value || !(expiresAt > Date.now())) isolateSessions.delete(key)\n else {\n const entry = isolateSessions.get(key)\n if (entry) entry.until = Math.min(entry.until, expiresAt)\n }\n return value\n }, (error) => { isolateSessions.delete(key); throw error })\n isolateSessions.delete(key)\n isolateSessions.set(key, { until: now + ttlMs, session })\n if (isolateSessions.size > SESSION_MEMO_LIMIT) isolateSessions.delete(isolateSessions.keys().next().value!)\n requestSessions.set(request, session)\n return session\n}\n\nfunction forgetSessions(scope: string): void {\n for (const key of isolateSessions.keys()) if (key.startsWith(`${scope}\\u0000`)) isolateSessions.delete(key)\n}\n\n/** Structural slice of a Resend-style client — no `resend` import. */\nexport interface AppAuthEmailClient {\n emails: {\n send(message: {\n from: string\n to: string\n subject: string\n html: string\n text?: string\n /** Inline images the HTML references by `cid:`, such as the Tangle mark. */\n attachments?: EmailAttachment[]\n }): Promise<unknown>\n }\n}\n\n/** Define email configuration for app authentication including client, sender, verification, and warning options */\nexport interface AppAuthEmailConfig {\n /** A Resend-style client, or a lazy getter returning null when the API key\n * is absent (the products' dev default — mail is skipped with a warning,\n * sign-up itself must not crash). */\n resend: AppAuthEmailClient | (() => AppAuthEmailClient | null)\n /** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */\n from: string\n /** Send a verification email on sign-up and auto-sign-in after verifying\n * (the tax/gtm behavior). Default false (the legal behavior). */\n verifyOnSignUp?: boolean\n /** Receives the \"email client unavailable\" warning. Default console.warn. */\n warn?: (message: string) => void\n}\n\n/** Env-shaped: pass the env vars straight through; the provider is registered\n * only when BOTH values are non-empty, so unset env disables it. */\nexport interface AppAuthSocialProviderConfig {\n clientId?: string\n clientSecret?: string\n}\n\n/** Define social authentication configuration options for GitHub and Google providers */\nexport interface AppAuthSocialConfig {\n github?: AppAuthSocialProviderConfig\n google?: AppAuthSocialProviderConfig\n}\n\n/** Cross-site Tangle SSO wiring. The factory supplies the better-auth side —\n * `setSessionCookie` via `createBetterAuthSessionCookieMinter(auth)` (signed\n * `__Secure-`/prefixed cookie that `auth.api.getSession` accepts) — so the\n * product no longer touches `better-auth/crypto` itself. */\nexport interface AppAuthSsoConfig {\n protocol?: 'legacy'\n /** Platform wire client (authorizeUrl + exchange). */\n client: TangleSsoAuthClient\n /** Product persistence: user upsert, session row, platform link. */\n store: TangleSsoAccountStore\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n /** Default 'tangle_sso_state'. */\n stateCookieName?: string\n /** HMAC secret for the CSRF state cookie. Default: the auth `secret`. */\n stateSecret?: string\n /** Default: `baseURL` is https. Must match better-auth's own\n * secure-cookie decision or the cookie name lookup diverges. */\n secureCookies?: boolean\n sessionTtlSeconds?: number\n stateTtlSeconds?: number\n /** Post-login redirect fallback. Default '/app'. */\n defaultRedirectPath?: string\n /** Default: the top-level `loginPath`. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n}\n\n/** Registered OIDC client configuration. The caller supplies Runtime PKCE; login does not mint an API key. */\nexport interface AppAuthOidcSsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'oidc'\n client: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\n/** First-party identity login; no Platform API key is issued or stored. */\nexport interface AppAuthIdentitySsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'identity'\n client: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define the structure for application authentication data including users, sessions, accounts, and verifications */\nexport interface AppAuthSchema {\n users: unknown\n sessions: unknown\n accounts: unknown\n verifications: unknown\n}\n\n/** Define configuration settings for app authentication including app name, base URL, secrets, and trusted origins */\nexport interface AppAuthConfig {\n /** Product name — used in email subjects and as the cookie-prefix default. */\n appName: string\n /** Absolute origin better-auth serves from (`BETTER_AUTH_URL`). */\n baseURL: string\n /** better-auth HMAC secret. Optional only because better-auth falls back to\n * the BETTER_AUTH_SECRET env var; `sso` needs it explicitly (or\n * `sso.stateSecret`). */\n secret?: string\n trustedOrigins?: string[]\n /**\n * Session-cookie prefix. Default: slugified `appName`. A per-app prefix is\n * load-bearing, not cosmetic: the platform (id.tangle.tools) mints its own\n * better-auth cookie `Domain=.tangle.tools`-wide under the DEFAULT name, and\n * the platform's (older) cookie wins the Cookie-header order — an app on the\n * default prefix reads the platform's token, fails its own signature check,\n * and every fresh login lands back on /login.\n */\n cookiePrefix?: string\n /** Drizzle database instance; wired through better-auth's drizzle adapter\n * together with `schema`. */\n db?: unknown\n /** The product's users/sessions/accounts/verifications tables (mapped to\n * better-auth's user/session/account/verification models). */\n schema?: AppAuthSchema\n /** Drizzle dialect. Default 'sqlite' (D1). */\n provider?: 'sqlite' | 'pg' | 'mysql'\n /** Escape hatch: a pre-built better-auth database adapter (e.g.\n * `memoryAdapter` in tests). Wins over `db`/`schema`. */\n database?: BetterAuthOptions['database']\n /** Email+password sign-in. Default true (all current products enable it). */\n emailAndPassword?: boolean\n /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** Session cookie-cache TTL in seconds; `false` disables the cache.\n * Default 300. */\n sessionCookieCacheSeconds?: number | false\n /** Tangle cross-site SSO (start/callback handlers). */\n sso?: AppAuthSsoConfig | AppAuthOidcSsoConfig | AppAuthIdentitySsoConfig\n /** Where guards redirect unauthenticated page requests. Default '/login'. */\n loginPath?: string\n /** Merged over the factory's `advanced` block (cookiePrefix stays unless\n * overridden here). */\n advanced?: BetterAuthOptions['advanced']\n}\n\n/** The configured better-auth instance, typed at better-auth's base surface\n * (`handler`, `api`, `$context`, `$Infer`). */\nexport type AppAuthInstance = Auth\n\n/** What `getSession`/guards resolve: better-auth's base session + user rows. */\nexport interface AppAuthSession {\n session: Session\n user: User\n}\n\n/** Define authentication guard with session retrieval and optional SSO handlers for app requests */\nexport interface AppAuth extends AuthGuard<AppAuthSession> {\n auth: AppAuthInstance\n /** `auth.api.getSession` over a `Request` — the seam the guards consume. */\n getSession(request: Request): Promise<AppAuthSession | null>\n /** Tangle SSO start/callback handlers; null unless `sso` was configured. */\n sso: TangleSsoHandlers | null\n}\n\n/** Lowercased, non-alphanumerics collapsed to '-': `'Legal Agent'` → `'legal-agent'`. */\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction emailProduct(config: AppAuthConfig): EmailProduct {\n return { name: config.appName, url: config.baseURL }\n}\n\nfunction resolveEmailClient(email: AppAuthEmailConfig): AppAuthEmailClient | null {\n return typeof email.resend === 'function' ? email.resend() : email.resend\n}\n\ntype DrizzleAuthAdapter = ReturnType<ReturnType<typeof drizzleAdapter>>\n\n/** Better Auth reads adapter identity during startup, before Workers inject D1.\n * Build the Drizzle adapter on its first database operation. */\nfunction deferDrizzleAdapter(\n db: Record<string, unknown>,\n config: Parameters<typeof drizzleAdapter>[1],\n): ReturnType<typeof drizzleAdapter> {\n return (options) => {\n let adapter: DrizzleAuthAdapter | undefined\n const resolve = () => (adapter ??= drizzleAdapter(db, config)(options))\n\n return {\n id: 'drizzle',\n create: (data) => resolve().create(data),\n findOne: (data) => resolve().findOne(data),\n findMany: (data) => resolve().findMany(data),\n count: (data) => resolve().count(data),\n update: (data) => resolve().update(data),\n updateMany: (data) => resolve().updateMany(data),\n delete: (data) => resolve().delete(data),\n deleteMany: (data) => resolve().deleteMany(data),\n consumeOne: (data) => resolve().consumeOne(data),\n incrementOne: (data) => resolve().incrementOne(data),\n transaction: (callback) => resolve().transaction(callback),\n }\n }\n}\n\n/** Resend reports failures in the resolved value, not by rejecting — surface\n * them loud so better-auth's flow (and the caller's logs) see the failure. */\nasync function sendEmail(client: AppAuthEmailClient, from: string, to: string, message: EmailMessage): Promise<void> {\n const { subject, html, text, attachments } = message\n const result = (await client.emails.send({ from, to, subject, html, text, attachments })) as\n | { error?: { message?: string } | null }\n | null\n | undefined\n if (result && typeof result === 'object' && result.error) {\n throw new Error(`[app-auth] email send failed: ${result.error.message ?? 'unknown error'}`)\n }\n}\n\nfunction resolveDatabase(config: AppAuthConfig): NonNullable<BetterAuthOptions['database']> {\n if (config.database) return config.database\n if (config.db && config.schema) {\n return deferDrizzleAdapter(config.db as Record<string, unknown>, {\n provider: config.provider ?? 'sqlite',\n schema: {\n user: config.schema.users,\n session: config.schema.sessions,\n account: config.schema.accounts,\n verification: config.schema.verifications,\n } as Record<string, unknown>,\n })\n }\n throw new Error(\n 'createAppAuth requires a database: pass `db` + `schema` (drizzle) or `database` (a better-auth adapter)',\n )\n}\n\nfunction resolveSocialProviders(social: AppAuthSocialConfig | undefined): BetterAuthOptions['socialProviders'] {\n const providers: NonNullable<BetterAuthOptions['socialProviders']> = {}\n if (social?.github?.clientId && social.github.clientSecret) {\n providers.github = { clientId: social.github.clientId, clientSecret: social.github.clientSecret }\n }\n if (social?.google?.clientId && social.google.clientSecret) {\n providers.google = { clientId: social.google.clientId, clientSecret: social.google.clientSecret }\n }\n return Object.keys(providers).length > 0 ? providers : undefined\n}\n\nfunction emailAndPasswordOptions(config: AppAuthConfig): BetterAuthOptions['emailAndPassword'] {\n const email = config.email\n if (!email) return { enabled: true }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\n sendResetPassword: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — password reset email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Reset your password',\n title: 'Reset your password',\n body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,\n action: { label: 'Reset password', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: 'You received this because a password reset was requested for this address.' },\n }))\n },\n }\n}\n\nfunction emailVerificationOptions(config: AppAuthConfig): BetterAuthOptions['emailVerification'] {\n const email = config.email\n if (!email?.verifyOnSignUp) return undefined\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n sendOnSignUp: true,\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — verification email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Verify your email',\n title: 'Verify your email',\n body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,\n action: { label: 'Verify email', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` },\n }))\n },\n }\n}\n\n/**\n * Build the product's better-auth instance plus the request-boundary helpers:\n * `getSession` (Request → session|null), the `createAuthGuard` quartet\n * (`requireUser` 302, `requireApiUser` JSON 401, `requireSession`,\n * `getOptionalSession`), and — when `sso` is configured — the Tangle SSO\n * start/callback handlers with the session cookie minted through better-auth's\n * own name/attributes/signing (no `better-auth/crypto` in product code).\n */\nexport function createAppAuth(config: AppAuthConfig): AppAuth {\n if (!config.appName) throw new Error('createAppAuth: appName is required')\n if (!config.baseURL) throw new Error('createAppAuth: baseURL is required')\n\n const cookiePrefix = config.cookiePrefix ?? slugify(config.appName)\n if (!cookiePrefix) throw new Error('createAppAuth: cookiePrefix (or a slugifiable appName) is required')\n\n const socialProviders = resolveSocialProviders(config.social)\n const options: BetterAuthOptions = {\n appName: config.appName,\n baseURL: config.baseURL,\n ...(config.secret ? { secret: config.secret } : {}),\n ...(config.trustedOrigins ? { trustedOrigins: config.trustedOrigins } : {}),\n database: resolveDatabase(config),\n ...(config.emailAndPassword === false ? {} : { emailAndPassword: emailAndPasswordOptions(config) }),\n ...(config.email?.verifyOnSignUp ? { emailVerification: emailVerificationOptions(config) } : {}),\n ...(socialProviders ? { socialProviders } : {}),\n ...(config.sessionCookieCacheSeconds === false\n ? {}\n : {\n session: {\n cookieCache: {\n enabled: true,\n maxAge: config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS,\n },\n },\n }),\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n\n const readSession = async (request: Request): Promise<AppAuthSession | null> => {\n const session = await auth.api.getSession({ headers: request.headers })\n return (session as AppAuthSession | null) ?? null\n }\n const memoMs = config.sessionCookieCacheSeconds === false ? 0\n : Math.min(SESSION_MEMO_MAX_MS, (config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS) * 1000)\n const memoScope = `${config.baseURL}\\u0000${cookiePrefix}`\n const getSession = (request: Request): Promise<AppAuthSession | null> =>\n memoMs > 0 ? memoizedSession(memoScope, memoMs, request, readSession) : readSession(request)\n // Sign-out and session revocation drop this isolate's remembered sessions for the app.\n const handler = auth.handler\n auth.handler = async (request: Request) => {\n // In finally: a sign-out that fails after deleting the session must not leave it remembered.\n try { return await handler(request) }\n finally { if (request.method !== 'GET') forgetSessions(memoScope) }\n }\n\n const loginPath = config.loginPath ?? '/login'\n const guard = createAuthGuard<AppAuthSession>({ getSession, loginPath })\n\n let sso: TangleSsoHandlers | null = null\n if (config.sso) {\n const stateSecret = config.sso.stateSecret ?? config.secret\n if (!stateSecret) {\n throw new Error(\n 'createAppAuth: sso requires `secret` (or sso.stateSecret) — the signed-state CSRF cookie needs an HMAC secret',\n )\n }\n const transport = config.sso.protocol === 'oidc'\n ? { protocol: 'oidc' as const, auth: config.sso.client, store: config.sso.store, createPkcePair: config.sso.createPkcePair }\n : config.sso.protocol === 'identity'\n ? { protocol: 'identity' as const, auth: config.sso.client, store: config.sso.store }\n : { protocol: 'legacy' as const, auth: config.sso.client, store: config.sso.store }\n sso = createTangleSsoHandlers({\n ...transport,\n stateSecret,\n callbackUrl: config.sso.callbackUrl,\n stateCookieName: config.sso.stateCookieName ?? DEFAULT_STATE_COOKIE,\n setSessionCookie: createBetterAuthSessionCookieMinter(auth),\n secureCookies: config.sso.secureCookies ?? config.baseURL.startsWith('https:'),\n ...(config.sso.sessionTtlSeconds !== undefined ? { sessionTtlSeconds: config.sso.sessionTtlSeconds } : {}),\n ...(config.sso.stateTtlSeconds !== undefined ? { stateTtlSeconds: config.sso.stateTtlSeconds } : {}),\n ...(config.sso.defaultRedirectPath ? { defaultRedirectPath: config.sso.defaultRedirectPath } : {}),\n loginPath: config.sso.loginPath ?? loginPath,\n ...(config.sso.log ? { log: config.sso.log } : {}),\n })\n }\n\n return { auth, getSession, ...guard, sso }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,SAAS,kBAA8E;AACvF,SAAS,sBAAsB;AAe/B,IAAM,uBAAuB;AAC7B,IAAM,uCAAuC,IAAI;AAUjD,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB,oBAAI,QAAiD;AAC7E,IAAM,kBAAkB,oBAAI,IAAwE;AAEpG,SAAS,gBAAgB,OAAe,OAAe,SACrD,MAA4F;AAC5F,QAAM,QAAQ,gBAAgB,IAAI,OAAO;AACzC,MAAI,MAAO,QAAO;AAClB,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,QAAM,gBAAgB,QAAQ,QAAQ,IAAI,eAAe,KAAK;AAC9D,MAAI,CAAC,UAAU,CAAC,cAAe,QAAO,KAAK,OAAO;AAClD,QAAM,MAAM,GAAG,KAAK,KAAS,aAAa,KAAS,MAAM;AACzD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,MAAM,gBAAgB,IAAI,GAAG;AACnC,MAAI,OAAO,IAAI,QAAQ,KAAK;AAC1B,oBAAgB,IAAI,SAAS,IAAI,OAAO;AACxC,WAAO,IAAI;AAAA,EACb;AACA,QAAM,UAAU,KAAK,OAAO,EAAE,KAAK,CAAC,UAAU;AAE5C,UAAM,YAAY,QAAQ,IAAI,KAAK,MAAM,QAAQ,SAAS,EAAE,QAAQ,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,eAAe,IACzH,OAAO,IAAI,aAAa,aACtB,EAAE,UAAU,YAAqB,MAAM,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,MAAM,IACpF,EAAE,UAAU,UAAmB,MAAM,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,MAAM;AACpF,UAAM,wBAAwB;AAAA,MAC5B,GAAG;AAAA,MACH;AAAA,MACA,aAAa,OAAO,IAAI;AAAA,MACxB,iBAAiB,OAAO,IAAI,mBAAmB;AAAA,MAC/C,kBAAkB,oCAAoC,IAAI;AAAA,MAC1D,eAAe,OAAO,IAAI,iBAAiB,OAAO,QAAQ,WAAW,QAAQ;AAAA,MAC7E,GAAI,OAAO,IAAI,sBAAsB,SAAY,EAAE,mBAAmB,OAAO,IAAI,kBAAkB,IAAI,CAAC;AAAA,MACxG,GAAI,OAAO,IAAI,oBAAoB,SAAY,EAAE,iBAAiB,OAAO,IAAI,gBAAgB,IAAI,CAAC;AAAA,MAClG,GAAI,OAAO,IAAI,sBAAsB,EAAE,qBAAqB,OAAO,IAAI,oBAAoB,IAAI,CAAC;AAAA,MAChG,WAAW,OAAO,IAAI,aAAa;AAAA,MACnC,GAAI,OAAO,IAAI,MAAM,EAAE,KAAK,OAAO,IAAI,IAAI,IAAI,CAAC;AAAA,IAClD,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,MAAM,YAAY,GAAG,OAAO,IAAI;AAC3C;","names":[]}
|
|
@@ -1733,14 +1733,15 @@ async function provisionWorkspaceSandbox(shell, options) {
|
|
|
1733
1733
|
throw new Error("livenessProbe.execTimeoutMs must be an integer between 100 and 600000");
|
|
1734
1734
|
}
|
|
1735
1735
|
const { workspaceId, userId, harness, forceNew, onProgress, billingOwnerId } = options;
|
|
1736
|
-
const
|
|
1736
|
+
const measure = (stage, operation) => options.measure ? options.measure(`sandbox.ensure.${stage}`, operation) : operation();
|
|
1737
|
+
const resolved = await measure("credentials", () => resolveWorkspaceSandboxClient(shell, workspaceId, userId));
|
|
1737
1738
|
const { scope, client } = resolved;
|
|
1738
1739
|
let name = resolved.name;
|
|
1739
1740
|
let recoveryRestore;
|
|
1740
1741
|
let replacementRequested = false;
|
|
1741
1742
|
const resources = shell.resources ?? DEFAULT_SANDBOX_RESOURCES;
|
|
1742
1743
|
const resumeTimeout = shell.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS;
|
|
1743
|
-
let existing = await listRunning(client, name);
|
|
1744
|
+
let existing = await measure("list_running", () => listRunning(client, name));
|
|
1744
1745
|
if (forceNew && existing.succeeded && !existing.value) {
|
|
1745
1746
|
existing = await listStopped(client, name);
|
|
1746
1747
|
}
|
|
@@ -1753,11 +1754,17 @@ async function provisionWorkspaceSandbox(shell, options) {
|
|
|
1753
1754
|
throw new Error(`forceNew: sandbox ${name} could not be deleted`, { cause: dropped.error });
|
|
1754
1755
|
}
|
|
1755
1756
|
} else if (found.metadata?.harness === harness) {
|
|
1756
|
-
const
|
|
1757
|
+
const [envResult, readyResult] = await Promise.allSettled([
|
|
1758
|
+
measure("runtime_env", () => resolveWorkspaceRuntimeEnv(shell, scope)),
|
|
1759
|
+
measure("refresh", () => refreshRuntimeConnection(client, found))
|
|
1760
|
+
]);
|
|
1761
|
+
if (envResult.status === "rejected") throw envResult.reason;
|
|
1762
|
+
const runtimeEnv2 = envResult.value;
|
|
1757
1763
|
try {
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1764
|
+
if (readyResult.status === "rejected") throw readyResult.reason;
|
|
1765
|
+
const ready = readyResult.value;
|
|
1766
|
+
if ((await measure("liveness", () => isReusableBox(ready, shell.livenessProbe))).succeeded) {
|
|
1767
|
+
return await measure("finalize", () => finalizeExistingBox(shell, client, ready, "reused", name, workspaceId, userId, harness, scope, runtimeEnv2));
|
|
1761
1768
|
}
|
|
1762
1769
|
const recovered = await recoverUnresponsiveBox(
|
|
1763
1770
|
client,
|
|
@@ -2594,4 +2601,4 @@ export {
|
|
|
2594
2601
|
isTerminalPromptEvent,
|
|
2595
2602
|
detectInteractiveQuestion
|
|
2596
2603
|
};
|
|
2597
|
-
//# sourceMappingURL=chunk-
|
|
2604
|
+
//# sourceMappingURL=chunk-7DG6GGRN.js.map
|