@tangle-network/agent-app 0.58.20 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VaultPane-OH4W5MXW.js +7 -0
- package/dist/app-auth/index.d.ts +6 -3
- package/dist/app-auth/index.js +26 -23
- package/dist/app-auth/index.js.map +1 -1
- package/dist/assistant/index.js +1 -1
- package/dist/chat-routes/index.js +1 -1
- package/dist/chunk-AB63T2LM.js +32 -0
- package/dist/chunk-AB63T2LM.js.map +1 -0
- package/dist/{chunk-QPMEXMH6.js → chunk-FMX3IOJM.js} +1 -1
- package/dist/{chunk-QPMEXMH6.js.map → chunk-FMX3IOJM.js.map} +1 -1
- package/dist/{chunk-CJW24QMJ.js → chunk-SUIHWGQT.js} +8 -1
- package/dist/chunk-SUIHWGQT.js.map +1 -0
- package/dist/chunk-YPPVNQOC.js +413 -0
- package/dist/chunk-YPPVNQOC.js.map +1 -0
- package/dist/email/index.d.ts +25 -0
- package/dist/email/index.js +19 -0
- package/dist/email/index.js.map +1 -0
- package/dist/email/layout.d.ts +77 -0
- package/dist/email/lint.d.ts +12 -0
- package/dist/email/mark.generated.d.ts +2 -0
- package/dist/email/palette.d.ts +40 -0
- package/dist/email/templates.d.ts +69 -0
- package/dist/sandbox/index.d.ts +10 -0
- package/dist/sandbox/index.js +1 -1
- package/dist/teams/index.js +2 -4
- package/dist/teams/invitations-api.d.ts +1 -1
- package/dist/teams/invitations-api.js +4 -4
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/teams/invitations.d.ts +4 -37
- package/dist/vault/index.js +1 -1
- package/dist/vault/lazy.js +1 -1
- package/dist/vault/recent-files.d.ts +0 -2
- package/dist/web-react/index.js +1 -1
- package/package.json +6 -1
- package/dist/VaultPane-UNX4CWSM.js +0 -7
- package/dist/chunk-2DRYTJHI.js +0 -58
- package/dist/chunk-2DRYTJHI.js.map +0 -1
- package/dist/chunk-CJW24QMJ.js.map +0 -1
- /package/dist/{VaultPane-UNX4CWSM.js.map → VaultPane-OH4W5MXW.js.map} +0 -0
package/dist/app-auth/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* better-auth config factory for agent products (#188 Phase 1). Every product
|
|
3
3
|
* hand-rolls the same ~70–150 line setup — drizzle adapter over the standard
|
|
4
|
-
* users/sessions/accounts/verifications tables, email+password with
|
|
5
|
-
* reset/verification mail, env-gated GitHub/Google social providers, session
|
|
4
|
+
* users/sessions/accounts/verifications tables, email+password with branded
|
|
5
|
+
* reset/verification mail (`./email`), env-gated GitHub/Google social providers, session
|
|
6
6
|
* cookie cache, and a per-app cookie prefix — and tax additionally
|
|
7
7
|
* re-implemented better-auth's cookie signing for its Tangle SSO callback.
|
|
8
8
|
* `createAppAuth` owns that mechanism once and returns the configured
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* deliberately NOT re-exported from the root barrel.
|
|
19
19
|
*/
|
|
20
20
|
import { type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth';
|
|
21
|
+
import { type EmailAttachment } from '../email';
|
|
21
22
|
import { type AuthGuard } from '../platform/guards';
|
|
22
23
|
import { type TangleSsoAccountStore, type TangleSsoAuthClient, type TangleSsoHandlers, type TangleIdentitySsoAccountStore, type TangleIdentitySsoAuthClient, type TangleOidcSsoAccountStore, type TangleOidcSsoAuthClient } from '../platform/sso';
|
|
23
24
|
/** Structural slice of a Resend-style client — no `resend` import. */
|
|
@@ -29,6 +30,8 @@ export interface AppAuthEmailClient {
|
|
|
29
30
|
subject: string;
|
|
30
31
|
html: string;
|
|
31
32
|
text?: string;
|
|
33
|
+
/** Inline images the HTML references by `cid:`, such as the Tangle mark. */
|
|
34
|
+
attachments?: EmailAttachment[];
|
|
32
35
|
}): Promise<unknown>;
|
|
33
36
|
};
|
|
34
37
|
}
|
|
@@ -38,7 +41,7 @@ export interface AppAuthEmailConfig {
|
|
|
38
41
|
* is absent (the products' dev default — mail is skipped with a warning,
|
|
39
42
|
* sign-up itself must not crash). */
|
|
40
43
|
resend: AppAuthEmailClient | (() => AppAuthEmailClient | null);
|
|
41
|
-
/** RFC 5322 From
|
|
44
|
+
/** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */
|
|
42
45
|
from: string;
|
|
43
46
|
/** Send a verification email on sign-up and auto-sign-in after verifying
|
|
44
47
|
* (the tax/gtm behavior). Default false (the legal behavior). */
|
package/dist/app-auth/index.js
CHANGED
|
@@ -3,6 +3,9 @@ import {
|
|
|
3
3
|
createBetterAuthSessionCookieMinter,
|
|
4
4
|
createTangleSsoHandlers
|
|
5
5
|
} from "../chunk-WN3UK23P.js";
|
|
6
|
+
import {
|
|
7
|
+
noticeEmail
|
|
8
|
+
} from "../chunk-YPPVNQOC.js";
|
|
6
9
|
import "../chunk-D6UJEOZQ.js";
|
|
7
10
|
import "../chunk-YNSPVKMS.js";
|
|
8
11
|
import "../chunk-3NCPXNBZ.js";
|
|
@@ -16,6 +19,9 @@ var DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60;
|
|
|
16
19
|
function slugify(name) {
|
|
17
20
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
18
21
|
}
|
|
22
|
+
function emailProduct(config) {
|
|
23
|
+
return { name: config.appName, url: config.baseURL };
|
|
24
|
+
}
|
|
19
25
|
function resolveEmailClient(email) {
|
|
20
26
|
return typeof email.resend === "function" ? email.resend() : email.resend;
|
|
21
27
|
}
|
|
@@ -39,8 +45,9 @@ function deferDrizzleAdapter(db, config) {
|
|
|
39
45
|
};
|
|
40
46
|
};
|
|
41
47
|
}
|
|
42
|
-
async function sendEmail(client, message) {
|
|
43
|
-
const
|
|
48
|
+
async function sendEmail(client, from, to, message) {
|
|
49
|
+
const { subject, html, text, attachments } = message;
|
|
50
|
+
const result = await client.emails.send({ from, to, subject, html, text, attachments });
|
|
44
51
|
if (result && typeof result === "object" && result.error) {
|
|
45
52
|
throw new Error(`[app-auth] email send failed: ${result.error.message ?? "unknown error"}`);
|
|
46
53
|
}
|
|
@@ -84,17 +91,15 @@ function emailAndPasswordOptions(config) {
|
|
|
84
91
|
warn("[app-auth] email client unavailable \u2014 password reset email not sent");
|
|
85
92
|
return;
|
|
86
93
|
}
|
|
87
|
-
await sendEmail(client, {
|
|
88
|
-
from: email.from,
|
|
89
|
-
to: user.email,
|
|
94
|
+
await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {
|
|
90
95
|
subject: "Reset your password",
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
});
|
|
96
|
+
title: "Reset your password",
|
|
97
|
+
body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,
|
|
98
|
+
action: { label: "Reset password", url },
|
|
99
|
+
showLink: true,
|
|
100
|
+
note: "This link expires in 1 hour.",
|
|
101
|
+
footer: { reason: "You received this because a password reset was requested for this address." }
|
|
102
|
+
}));
|
|
98
103
|
}
|
|
99
104
|
};
|
|
100
105
|
}
|
|
@@ -111,17 +116,15 @@ function emailVerificationOptions(config) {
|
|
|
111
116
|
warn("[app-auth] email client unavailable \u2014 verification email not sent");
|
|
112
117
|
return;
|
|
113
118
|
}
|
|
114
|
-
await sendEmail(client, {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
${
|
|
122
|
-
|
|
123
|
-
This link expires in 1 hour.`
|
|
124
|
-
});
|
|
119
|
+
await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {
|
|
120
|
+
subject: "Verify your email",
|
|
121
|
+
title: "Verify your email",
|
|
122
|
+
body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,
|
|
123
|
+
action: { label: "Verify email", url },
|
|
124
|
+
showLink: true,
|
|
125
|
+
note: "This link expires in 1 hour.",
|
|
126
|
+
footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` }
|
|
127
|
+
}));
|
|
125
128
|
}
|
|
126
129
|
};
|
|
127
130
|
}
|
|
@@ -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 Resend\n * reset/verification mail, 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 { 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 }): 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, e.g. `'Legal Agent <noreply@legal.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 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(\n client: AppAuthEmailClient,\n message: { from: string; to: string; subject: string; html: string; text: string },\n): Promise<void> {\n const result = (await client.emails.send(message)) as { error?: { message?: string } | null } | null | 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, {\n from: email.from,\n to: user.email,\n subject: 'Reset your password',\n html: `<p>Click the link below to reset your password:</p><p><a href=\"${url}\">${url}</a></p><p>This link expires in 1 hour.</p>`,\n text: `Reset your password:\\n\\n${url}\\n\\nThis link expires in 1 hour.`,\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, {\n from: email.from,\n to: user.email,\n subject: `Verify your ${config.appName} email`,\n html: `<p>Verify your email to finish accessing ${config.appName}:</p><p><a href=\"${url}\">${url}</a></p><p>This link expires in 1 hour.</p>`,\n text: `Verify your email to finish accessing ${config.appName}:\\n\\n${url}\\n\\nThis link expires in 1 hour.`,\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;AAc/B,IAAM,uBAAuB;AAC7B,IAAM,uCAAuC,IAAI;AAoKjD,SAAS,QAAQ,MAAsB;AACrC,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAC3B;AAEA,SAAS,mBAAmB,OAAsD;AAChF,SAAO,OAAO,MAAM,WAAW,aAAa,MAAM,OAAO,IAAI,MAAM;AACrE;AAMA,SAAS,oBACP,IACA,QACmC;AACnC,SAAO,CAAC,YAAY;AAClB,QAAI;AACJ,UAAM,UAAU,MAAO,YAAY,eAAe,IAAI,MAAM,EAAE,OAAO;AAErE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,CAAC,SAAS,QAAQ,EAAE,OAAO,IAAI;AAAA,MACvC,SAAS,CAAC,SAAS,QAAQ,EAAE,QAAQ,IAAI;AAAA,MACzC,UAAU,CAAC,SAAS,QAAQ,EAAE,SAAS,IAAI;AAAA,MAC3C,OAAO,CAAC,SAAS,QAAQ,EAAE,MAAM,IAAI;AAAA,MACrC,QAAQ,CAAC,SAAS,QAAQ,EAAE,OAAO,IAAI;AAAA,MACvC,YAAY,CAAC,SAAS,QAAQ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
|
|
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,SAAS,oBACP,IACA,QACmC;AACnC,SAAO,CAAC,YAAY;AAClB,QAAI;AACJ,UAAM,UAAU,MAAO,YAAY,eAAe,IAAI,MAAM,EAAE,OAAO;AAErE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,CAAC,SAAS,QAAQ,EAAE,OAAO,IAAI;AAAA,MACvC,SAAS,CAAC,SAA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AAW,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":[]}
|
package/dist/assistant/index.js
CHANGED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/teams/invitations.ts
|
|
2
|
+
var INVITATION_EXPIRY_DAYS = 7;
|
|
3
|
+
var INVITATION_PERMISSIONS = ["admin", "editor", "viewer"];
|
|
4
|
+
var TOKEN_BYTE_LENGTH = 32;
|
|
5
|
+
function normalizeInvitationEmail(email) {
|
|
6
|
+
return email.trim().toLowerCase();
|
|
7
|
+
}
|
|
8
|
+
function parseInvitationPermission(value) {
|
|
9
|
+
return INVITATION_PERMISSIONS.includes(value) ? value : null;
|
|
10
|
+
}
|
|
11
|
+
function getInvitationExpiresAt(now = /* @__PURE__ */ new Date()) {
|
|
12
|
+
return new Date(now.getTime() + INVITATION_EXPIRY_DAYS * 24 * 60 * 60 * 1e3);
|
|
13
|
+
}
|
|
14
|
+
function generateInvitationToken() {
|
|
15
|
+
const bytes = new Uint8Array(TOKEN_BYTE_LENGTH);
|
|
16
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
17
|
+
const token = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
|
|
18
|
+
return `inv_${btoa(token).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "")}`;
|
|
19
|
+
}
|
|
20
|
+
function inviteUrlForToken(origin, token) {
|
|
21
|
+
return `${origin.replace(/\/+$/, "")}/invite/${encodeURIComponent(token)}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
INVITATION_EXPIRY_DAYS,
|
|
26
|
+
normalizeInvitationEmail,
|
|
27
|
+
parseInvitationPermission,
|
|
28
|
+
getInvitationExpiresAt,
|
|
29
|
+
generateInvitationToken,
|
|
30
|
+
inviteUrlForToken
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=chunk-AB63T2LM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/teams/invitations.ts"],"sourcesContent":["/**\n * Pure invitation helpers for the teams capability. Zero dependencies: no\n * drizzle, no env, no react, no network. The lifecycle API (`./invitations-api`)\n * and an app's own mail transport build on these; the invitation email itself\n * is `inviteEmail` from `@tangle-network/agent-app/email`.\n */\n\nimport type { AssignableWorkspaceRole } from './roles'\n\n/** The role an invitation grants — the assignable workspace ladder (never owner). */\nexport type InvitationPermission = AssignableWorkspaceRole\n\n/** Define possible states for an invitation's lifecycle including pending, accepted, expired, and revoked */\nexport type InvitationStatus = 'pending' | 'accepted' | 'expired' | 'revoked'\n/** Define possible statuses for the sending state of an invitation email */\nexport type InvitationEmailStatus = 'not_sent' | 'sent' | 'failed'\n\n/** Define the number of days before an invitation expires */\nexport const INVITATION_EXPIRY_DAYS = 7\n\nconst INVITATION_PERMISSIONS = ['admin', 'editor', 'viewer'] as const\nconst TOKEN_BYTE_LENGTH = 32\n\n/** Normalize an invitation email by trimming whitespace and converting to lowercase */\nexport function normalizeInvitationEmail(email: string): string {\n return email.trim().toLowerCase()\n}\n\n/** Resolve invitation permission from a string or return null if invalid */\nexport function parseInvitationPermission(value: string | undefined): InvitationPermission | null {\n return INVITATION_PERMISSIONS.includes(value as InvitationPermission) ? (value as InvitationPermission) : null\n}\n\n/** Calculate the expiration date of an invitation based on the given or current date */\nexport function getInvitationExpiresAt(now: Date = new Date()): Date {\n return new Date(now.getTime() + INVITATION_EXPIRY_DAYS * 24 * 60 * 60 * 1000)\n}\n\n/**\n * A cryptographically-random, URL-safe invitation token. `inv_`-prefixed so a\n * token is self-identifying and never collides with the workspaceMember invite\n * tokens minted by `members-api` (`generateInviteToken`).\n */\nexport function generateInvitationToken(): string {\n const bytes = new Uint8Array(TOKEN_BYTE_LENGTH)\n globalThis.crypto.getRandomValues(bytes)\n const token = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')\n return `inv_${btoa(token).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '')}`\n}\n\n/** Generate an invite URL by combining the origin with an encoded token */\nexport function inviteUrlForToken(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, '')}/invite/${encodeURIComponent(token)}`\n}\n"],"mappings":";AAkBO,IAAM,yBAAyB;AAEtC,IAAM,yBAAyB,CAAC,SAAS,UAAU,QAAQ;AAC3D,IAAM,oBAAoB;AAGnB,SAAS,yBAAyB,OAAuB;AAC9D,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAGO,SAAS,0BAA0B,OAAwD;AAChG,SAAO,uBAAuB,SAAS,KAA6B,IAAK,QAAiC;AAC5G;AAGO,SAAS,uBAAuB,MAAY,oBAAI,KAAK,GAAS;AACnE,SAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,yBAAyB,KAAK,KAAK,KAAK,GAAI;AAC9E;AAOO,SAAS,0BAAkC;AAChD,QAAM,QAAQ,IAAI,WAAW,iBAAiB;AAC9C,aAAW,OAAO,gBAAgB,KAAK;AACvC,QAAM,QAAQ,MAAM,KAAK,OAAO,CAAC,SAAS,OAAO,aAAa,IAAI,CAAC,EAAE,KAAK,EAAE;AAC5E,SAAO,OAAO,KAAK,KAAK,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,QAAQ,EAAE,CAAC;AACvF;AAGO,SAAS,kBAAkB,QAAgB,OAAuB;AACvE,SAAO,GAAG,OAAO,QAAQ,QAAQ,EAAE,CAAC,WAAW,mBAAmB,KAAK,CAAC;AAC1E;","names":[]}
|