@buildspacestudio/sdk 0.3.0 → 0.4.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/README.md +126 -0
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +3 -118
- package/dist/auth/index.d.ts +3 -118
- package/dist/auth/index.js.map +1 -1
- package/dist/billing/index.cjs +226 -0
- package/dist/billing/index.cjs.map +1 -0
- package/dist/billing/index.d.cts +60 -0
- package/dist/billing/index.d.ts +60 -0
- package/dist/billing/index.js +222 -0
- package/dist/billing/index.js.map +1 -0
- package/dist/client/index.cjs +130 -0
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +7 -3
- package/dist/client/index.d.ts +7 -3
- package/dist/client/index.js +130 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client-BYUWUiGZ.d.cts +143 -0
- package/dist/{client-BH7LbrKM.d.ts → client-ByNR5EZz.d.ts} +1 -1
- package/dist/{client-C67hy1kt.d.cts → client-D0vypxWb.d.cts} +1 -1
- package/dist/{client-DqWXAwCr.d.cts → client-D7bqvGJv.d.cts} +1 -1
- package/dist/{client-Dlif1JBf.d.ts → client-DbGRRMt7.d.ts} +1 -1
- package/dist/client-d7kX5WfR.d.ts +143 -0
- package/dist/events/index.d.cts +2 -2
- package/dist/events/index.d.ts +2 -2
- package/dist/{http-U-zzKmFF.d.cts → http-D2gXpNpr.d.cts} +2 -2
- package/dist/{http-U-zzKmFF.d.ts → http-D2gXpNpr.d.ts} +2 -2
- package/dist/index.cjs +228 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -8
- package/dist/index.d.ts +13 -8
- package/dist/index.js +226 -1
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +183 -0
- package/dist/next/index.cjs.map +1 -0
- package/dist/next/index.d.cts +164 -0
- package/dist/next/index.d.ts +164 -0
- package/dist/next/index.js +172 -0
- package/dist/next/index.js.map +1 -0
- package/dist/notifications/index.d.cts +1 -1
- package/dist/notifications/index.d.ts +1 -1
- package/dist/react/index.cjs +120 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +567 -0
- package/dist/react/index.d.ts +567 -0
- package/dist/react/index.js +92 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server-CoPDzSUP.d.cts +117 -0
- package/dist/server-Suq3tZZC.d.ts +117 -0
- package/dist/storage/index.cjs.map +1 -1
- package/dist/storage/index.d.cts +1 -1
- package/dist/storage/index.d.ts +1 -1
- package/dist/storage/index.js.map +1 -1
- package/package.json +51 -2
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
var BuildspaceError = class extends Error {
|
|
5
|
+
/** Machine-readable error code, e.g. `"auth/invalid-token"`. */
|
|
6
|
+
code;
|
|
7
|
+
/** Which service produced the error. */
|
|
8
|
+
service;
|
|
9
|
+
/** HTTP status code from the API. */
|
|
10
|
+
status;
|
|
11
|
+
constructor({
|
|
12
|
+
code,
|
|
13
|
+
message,
|
|
14
|
+
service,
|
|
15
|
+
status
|
|
16
|
+
}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "BuildspaceError";
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.service = service;
|
|
21
|
+
this.status = status;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// src/next/index.ts
|
|
26
|
+
var SESSION_COOKIE_NAME = "bs_session";
|
|
27
|
+
function isSecureDefault() {
|
|
28
|
+
return globalThis.process?.env?.NODE_ENV !== "development";
|
|
29
|
+
}
|
|
30
|
+
function serializeSessionCookie(value, maxAge, opts) {
|
|
31
|
+
const parts = [
|
|
32
|
+
`${SESSION_COOKIE_NAME}=${value}`,
|
|
33
|
+
`Path=${opts?.path ?? "/"}`,
|
|
34
|
+
"HttpOnly",
|
|
35
|
+
`SameSite=${opts?.sameSite === "strict" ? "Strict" : opts?.sameSite === "none" ? "None" : "Lax"}`
|
|
36
|
+
];
|
|
37
|
+
if (maxAge !== null) {
|
|
38
|
+
parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);
|
|
39
|
+
}
|
|
40
|
+
if (opts?.secure ?? isSecureDefault()) {
|
|
41
|
+
parts.push("Secure");
|
|
42
|
+
}
|
|
43
|
+
if (opts?.domain) {
|
|
44
|
+
parts.push(`Domain=${opts.domain}`);
|
|
45
|
+
}
|
|
46
|
+
return parts.join("; ");
|
|
47
|
+
}
|
|
48
|
+
function buildSessionCookie(token, maxAgeSeconds, opts) {
|
|
49
|
+
return serializeSessionCookie(token, maxAgeSeconds, opts);
|
|
50
|
+
}
|
|
51
|
+
function buildClearSessionCookie(opts) {
|
|
52
|
+
return serializeSessionCookie("", 0, opts);
|
|
53
|
+
}
|
|
54
|
+
function parseCookieHeader(header, name) {
|
|
55
|
+
for (const part of header.split(";")) {
|
|
56
|
+
const eq = part.indexOf("=");
|
|
57
|
+
if (eq === -1) {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (part.slice(0, eq).trim() === name) {
|
|
61
|
+
return part.slice(eq + 1).trim();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
function getSessionToken(source) {
|
|
67
|
+
if (source instanceof Request) {
|
|
68
|
+
const header = source.headers.get("cookie");
|
|
69
|
+
return header ? parseCookieHeader(header, SESSION_COOKIE_NAME) : null;
|
|
70
|
+
}
|
|
71
|
+
const cookie = source.get(SESSION_COOKIE_NAME);
|
|
72
|
+
if (!cookie) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const value = typeof cookie === "string" ? cookie : cookie.value;
|
|
76
|
+
return value || null;
|
|
77
|
+
}
|
|
78
|
+
async function getSession(client, source) {
|
|
79
|
+
const token = getSessionToken(source);
|
|
80
|
+
if (!token) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const session = await client.auth.getSession(token);
|
|
85
|
+
return session ? { ...session, token } : null;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function requireSession(client, source) {
|
|
91
|
+
const session = await getSession(client, source);
|
|
92
|
+
if (!session) {
|
|
93
|
+
throw new BuildspaceError({
|
|
94
|
+
service: "auth",
|
|
95
|
+
status: 401,
|
|
96
|
+
code: "auth/session-required",
|
|
97
|
+
message: "No valid session. The bs_session cookie is missing, expired, or revoked."
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return session;
|
|
101
|
+
}
|
|
102
|
+
function createAuthCallback(client, options) {
|
|
103
|
+
return async (request) => {
|
|
104
|
+
let tokens;
|
|
105
|
+
try {
|
|
106
|
+
tokens = await client.auth.handleCallback(request);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (options?.onError) {
|
|
109
|
+
return await options.onError(error, request);
|
|
110
|
+
}
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
if (options?.onSignIn) {
|
|
114
|
+
try {
|
|
115
|
+
await options.onSignIn({
|
|
116
|
+
accessToken: tokens.access_token,
|
|
117
|
+
request,
|
|
118
|
+
user: tokens.user
|
|
119
|
+
});
|
|
120
|
+
} catch (error) {
|
|
121
|
+
console.error("[buildspace] onSignIn hook failed", error);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return new Response(null, {
|
|
125
|
+
status: 303,
|
|
126
|
+
headers: {
|
|
127
|
+
Location: options?.redirectTo ?? "/",
|
|
128
|
+
"Set-Cookie": buildSessionCookie(tokens.access_token, tokens.expires_in, options?.cookie)
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function createLogoutRoute(client, options) {
|
|
134
|
+
return async (request) => {
|
|
135
|
+
const token = getSessionToken(request);
|
|
136
|
+
if (token) {
|
|
137
|
+
try {
|
|
138
|
+
await client.auth.signOut(token);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
console.error("[buildspace] session revoke failed during logout", error);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return new Response(JSON.stringify({ ok: true }), {
|
|
144
|
+
status: 200,
|
|
145
|
+
headers: {
|
|
146
|
+
"Content-Type": "application/json",
|
|
147
|
+
"Set-Cookie": buildClearSessionCookie(options?.cookie)
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function createSessionRoute(client) {
|
|
153
|
+
return async (request) => {
|
|
154
|
+
const session = await getSession(client, request);
|
|
155
|
+
const publicSession = session ? { appId: session.appId, user: session.user } : null;
|
|
156
|
+
return new Response(JSON.stringify({ session: publicSession }), {
|
|
157
|
+
status: 200,
|
|
158
|
+
headers: { "Content-Type": "application/json" }
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function createSessionCookieGuard(options) {
|
|
163
|
+
return (request) => {
|
|
164
|
+
if (getSessionToken(request)) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const target = new URL(options?.redirectTo ?? "/", new URL(request.url).origin);
|
|
168
|
+
return Response.redirect(target.toString(), 307);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
exports.SESSION_COOKIE_NAME = SESSION_COOKIE_NAME;
|
|
173
|
+
exports.buildClearSessionCookie = buildClearSessionCookie;
|
|
174
|
+
exports.buildSessionCookie = buildSessionCookie;
|
|
175
|
+
exports.createAuthCallback = createAuthCallback;
|
|
176
|
+
exports.createLogoutRoute = createLogoutRoute;
|
|
177
|
+
exports.createSessionCookieGuard = createSessionCookieGuard;
|
|
178
|
+
exports.createSessionRoute = createSessionRoute;
|
|
179
|
+
exports.getSession = getSession;
|
|
180
|
+
exports.getSessionToken = getSessionToken;
|
|
181
|
+
exports.requireSession = requireSession;
|
|
182
|
+
//# sourceMappingURL=index.cjs.map
|
|
183
|
+
//# sourceMappingURL=index.cjs.map
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AU,EAAE,EAAA,EAAI,IAAA,EAAM,CAAA,EAAG;AAAA,MAChD,MAAA,EAAQ,GAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACP,cAAA,EAAgB,kBAAA;AAAA,QAChB,YAAA,EAAc,uBAAA,CAAwB,OAAA,EAAS,MAAM;AAAA;AACvD,KACD,CAAA;AAAA,EACH,CAAA;AACF;AAQO,SAAS,mBACd,MAAA,EACyC;AACzC,EAAA,OAAO,OAAO,OAAA,KAAwC;AACpD,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,MAAA,EAAQ,OAAO,CAAA;AAChD,IAAA,MAAM,aAAA,GAAgB,UAAU,EAAE,KAAA,EAAO,QAAQ,KAAA,EAAO,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAK,GAAI,IAAA;AAE/E,IAAA,OAAO,IAAI,SAAS,IAAA,CAAK,SAAA,CAAU,EAAE,OAAA,EAAS,aAAA,EAAe,CAAA,EAAG;AAAA,MAC9D,MAAA,EAAQ,GAAA;AAAA,MACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA;AAAmB,KAC/C,CAAA;AAAA,EACH,CAAA;AACF;AAkBO,SAAS,yBAAyB,OAAA,EAGM;AAC7C,EAAA,OAAO,CAAC,OAAA,KAA2C;AACjD,IAAA,IAAI,eAAA,CAAgB,OAAO,CAAA,EAAG;AAC5B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,OAAA,EAAS,UAAA,IAAc,GAAA,EAAK,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAM,CAAA;AAC9E,IAAA,OAAO,QAAA,CAAS,QAAA,CAAS,MAAA,CAAO,QAAA,IAAY,GAAG,CAAA;AAAA,EACjD,CAAA;AACF","file":"index.cjs","sourcesContent":["/** Services available in the Buildspace platform. */\nexport type BuildspaceService = \"auth\" | \"billing\" | \"events\" | \"notifications\" | \"storage\";\n\n/**\n * Error thrown by all Buildspace SDK methods on failure.\n *\n * @example\n * ```ts\n * try {\n * await buildspace.auth.getSession(token);\n * } catch (err) {\n * if (err instanceof BuildspaceError) {\n * console.error(err.service, err.code, err.status, err.message);\n * }\n * }\n * ```\n */\nexport class BuildspaceError extends Error {\n /** Machine-readable error code, e.g. `\"auth/invalid-token\"`. */\n readonly code: string;\n /** Which service produced the error. */\n readonly service: BuildspaceService;\n /** HTTP status code from the API. */\n readonly status: number;\n\n constructor({\n code,\n message,\n service,\n status,\n }: {\n code: string;\n message: string;\n service: BuildspaceService;\n status: number;\n }) {\n super(message);\n this.name = \"BuildspaceError\";\n this.code = code;\n this.service = service;\n this.status = status;\n }\n}\n","import type { AuthSession, AuthUser, TokenResponse } from \"../auth\";\nimport { BuildspaceError } from \"../errors\";\n\n/**\n * Framework adapter for Next.js (and any framework using web-standard\n * `Request`/`Response` route handlers).\n *\n * Replaces the auth glue every creator app used to hand-roll: the OAuth\n * callback route, logout + session routes, a cookie-aware `getSession()`,\n * and a middleware cookie guard — all standardized on the `bs_session`\n * cookie.\n *\n * @example\n * ```ts\n * // app/api/auth/callback/route.ts\n * import { createAuthCallback } from \"@buildspacestudio/sdk/next\";\n * import { getServerClient } from \"@/lib/buildspace\";\n *\n * export const GET = createAuthCallback(getServerClient(), { redirectTo: \"/dashboard\" });\n * ```\n */\n\n/** The session cookie name shared by every Buildspace app. */\nexport const SESSION_COOKIE_NAME = \"bs_session\";\n\n/** The minimal server-client surface the adapter needs (a `Buildspace` instance). */\nexport interface AuthServerClient {\n auth: {\n getSession(sessionToken: string): Promise<AuthSession | null>;\n handleCallback(\n request: Request | URL | string,\n opts?: { redirectUri?: string }\n ): Promise<TokenResponse>;\n signOut(sessionToken?: string): Promise<void>;\n };\n}\n\n/** Options controlling the `bs_session` cookie attributes. */\nexport interface SessionCookieOptions {\n /** Cookie domain. Omitted by default (host-only cookie). */\n domain?: string;\n /** Cookie path. Defaults to `/`. */\n path?: string;\n /** SameSite attribute. Defaults to `Lax`. */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /** Set the `Secure` attribute. Defaults to `true` outside development. */\n secure?: boolean;\n}\n\nfunction isSecureDefault(): boolean {\n return (\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n ?.NODE_ENV !== \"development\"\n );\n}\n\nfunction serializeSessionCookie(\n value: string,\n maxAge: number | null,\n opts?: SessionCookieOptions\n): string {\n const parts = [\n `${SESSION_COOKIE_NAME}=${value}`,\n `Path=${opts?.path ?? \"/\"}`,\n \"HttpOnly\",\n `SameSite=${opts?.sameSite === \"strict\" ? \"Strict\" : opts?.sameSite === \"none\" ? \"None\" : \"Lax\"}`,\n ];\n\n if (maxAge !== null) {\n parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);\n }\n\n if (opts?.secure ?? isSecureDefault()) {\n parts.push(\"Secure\");\n }\n\n if (opts?.domain) {\n parts.push(`Domain=${opts.domain}`);\n }\n\n return parts.join(\"; \");\n}\n\n/** Build a `Set-Cookie` header value that stores the session token. */\nexport function buildSessionCookie(\n token: string,\n maxAgeSeconds: number,\n opts?: SessionCookieOptions\n): string {\n return serializeSessionCookie(token, maxAgeSeconds, opts);\n}\n\n/** Build a `Set-Cookie` header value that clears the session cookie. */\nexport function buildClearSessionCookie(opts?: SessionCookieOptions): string {\n return serializeSessionCookie(\"\", 0, opts);\n}\n\n/**\n * Anything the adapter can read the session cookie from: a web `Request`,\n * or a cookie store with a `get(name)` method (e.g. the object returned by\n * Next.js `cookies()` in Server Components and Route Handlers).\n */\nexport type SessionCookieSource =\n | Request\n | {\n get(name: string): { value: string } | string | null | undefined;\n };\n\nfunction parseCookieHeader(header: string, name: string): string | null {\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n\n if (part.slice(0, eq).trim() === name) {\n return part.slice(eq + 1).trim();\n }\n }\n\n return null;\n}\n\n/** Read the raw session token from a request or cookie store, or `null`. */\nexport function getSessionToken(source: SessionCookieSource): string | null {\n if (source instanceof Request) {\n const header = source.headers.get(\"cookie\");\n return header ? parseCookieHeader(header, SESSION_COOKIE_NAME) : null;\n }\n\n const cookie = source.get(SESSION_COOKIE_NAME);\n if (!cookie) {\n return null;\n }\n\n const value = typeof cookie === \"string\" ? cookie : cookie.value;\n return value || null;\n}\n\n/** An {@link AuthSession} plus the raw token it was resolved from. */\nexport type SessionWithToken = AuthSession & { token: string };\n\n/**\n * Cookie-aware session lookup.\n *\n * Reads the `bs_session` cookie from the given source and verifies it with\n * the Buildspace API. Returns `null` when there is no cookie or the token\n * is expired/revoked. Network/5xx errors also resolve to `null` so a blip\n * never crashes rendering — sign-in state degrades to \"signed out\".\n *\n * @example\n * ```ts\n * // Server Component\n * import { cookies } from \"next/headers\";\n * const session = await getSession(getServerClient(), await cookies());\n * ```\n */\nexport async function getSession(\n client: AuthServerClient,\n source: SessionCookieSource\n): Promise<SessionWithToken | null> {\n const token = getSessionToken(source);\n if (!token) {\n return null;\n }\n\n try {\n const session = await client.auth.getSession(token);\n return session ? { ...session, token } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Like {@link getSession} but throws a `BuildspaceError` (401) when there is\n * no valid session. Use in route handlers and server actions that must only\n * run for signed-in users.\n */\nexport async function requireSession(\n client: AuthServerClient,\n source: SessionCookieSource\n): Promise<SessionWithToken> {\n const session = await getSession(client, source);\n if (!session) {\n throw new BuildspaceError({\n service: \"auth\",\n status: 401,\n code: \"auth/session-required\",\n message: \"No valid session. The bs_session cookie is missing, expired, or revoked.\",\n });\n }\n\n return session;\n}\n\n/** Options for {@link createAuthCallback}. */\nexport interface CreateAuthCallbackOptions {\n /** Cookie attribute overrides. */\n cookie?: SessionCookieOptions;\n /**\n * Called when the code exchange fails. Return a `Response` to control the\n * error page; by default the error is rethrown (surfacing your framework's\n * error handling).\n */\n onError?: (error: unknown, request: Request) => Response | Promise<Response>;\n /**\n * Signup/sign-in side effects (mirror the user into your DB, send a\n * welcome email, track an event). Failures are logged and never break\n * login.\n */\n onSignIn?: (ctx: {\n accessToken: string;\n request: Request;\n user: AuthUser;\n }) => void | Promise<void>;\n /** Where to send the user after login. Defaults to `/`. */\n redirectTo?: string;\n}\n\n/**\n * Create the OAuth callback route handler.\n *\n * Exchanges the `?code=` for tokens, runs your `onSignIn` hook, stores the\n * access token in the `bs_session` cookie (with `expires_in` as `Max-Age`),\n * and redirects to `redirectTo`.\n *\n * @example\n * ```ts\n * // app/api/auth/callback/route.ts\n * export const GET = createAuthCallback(getServerClient(), {\n * redirectTo: \"/dashboard\",\n * onSignIn: async ({ user }) => upsertUser(user),\n * });\n * ```\n */\nexport function createAuthCallback(\n client: AuthServerClient,\n options?: CreateAuthCallbackOptions\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n let tokens: TokenResponse;\n try {\n tokens = await client.auth.handleCallback(request);\n } catch (error) {\n if (options?.onError) {\n return await options.onError(error, request);\n }\n throw error;\n }\n\n if (options?.onSignIn) {\n try {\n await options.onSignIn({\n accessToken: tokens.access_token,\n request,\n user: tokens.user,\n });\n } catch (error) {\n console.error(\"[buildspace] onSignIn hook failed\", error);\n }\n }\n\n return new Response(null, {\n status: 303,\n headers: {\n Location: options?.redirectTo ?? \"/\",\n \"Set-Cookie\": buildSessionCookie(tokens.access_token, tokens.expires_in, options?.cookie),\n },\n });\n };\n}\n\n/**\n * Create the logout route handler (`POST /api/auth/logout`).\n *\n * Revokes the session with the Buildspace API (already-expired sessions are\n * ignored) and clears the `bs_session` cookie.\n */\nexport function createLogoutRoute(\n client: AuthServerClient,\n options?: { cookie?: SessionCookieOptions }\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const token = getSessionToken(request);\n\n if (token) {\n try {\n await client.auth.signOut(token);\n } catch (error) {\n console.error(\"[buildspace] session revoke failed during logout\", error);\n }\n }\n\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Set-Cookie\": buildClearSessionCookie(options?.cookie),\n },\n });\n };\n}\n\n/**\n * Create the session route handler (`GET /api/auth/session`).\n *\n * Returns `{ session }` for the current cookie, with the raw token omitted —\n * this response is safe to expose to the browser.\n */\nexport function createSessionRoute(\n client: AuthServerClient\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const session = await getSession(client, request);\n const publicSession = session ? { appId: session.appId, user: session.user } : null;\n\n return new Response(JSON.stringify({ session: publicSession }), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n };\n}\n\n/**\n * Middleware helper: redirect requests that don't carry a session cookie.\n *\n * This is a fast presence check (no API call — middleware runs on every\n * matched request); route handlers and pages must still verify the session\n * with {@link getSession}.\n *\n * @example\n * ```ts\n * // middleware.ts / proxy.ts\n * import { createSessionCookieGuard } from \"@buildspacestudio/sdk/next\";\n *\n * export const proxy = createSessionCookieGuard({ redirectTo: \"/\" });\n * export const config = { matcher: [\"/dashboard/:path*\"] };\n * ```\n */\nexport function createSessionCookieGuard(options?: {\n /** Where to send signed-out users. Defaults to `/`. */\n redirectTo?: string;\n}): (request: Request) => Response | undefined {\n return (request: Request): Response | undefined => {\n if (getSessionToken(request)) {\n return;\n }\n\n const target = new URL(options?.redirectTo ?? \"/\", new URL(request.url).origin);\n return Response.redirect(target.toString(), 307);\n };\n}\n"]}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { a as AuthSession, T as TokenResponse, b as AuthUser } from '../server-CoPDzSUP.cjs';
|
|
2
|
+
import '../http-D2gXpNpr.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Framework adapter for Next.js (and any framework using web-standard
|
|
6
|
+
* `Request`/`Response` route handlers).
|
|
7
|
+
*
|
|
8
|
+
* Replaces the auth glue every creator app used to hand-roll: the OAuth
|
|
9
|
+
* callback route, logout + session routes, a cookie-aware `getSession()`,
|
|
10
|
+
* and a middleware cookie guard — all standardized on the `bs_session`
|
|
11
|
+
* cookie.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* // app/api/auth/callback/route.ts
|
|
16
|
+
* import { createAuthCallback } from "@buildspacestudio/sdk/next";
|
|
17
|
+
* import { getServerClient } from "@/lib/buildspace";
|
|
18
|
+
*
|
|
19
|
+
* export const GET = createAuthCallback(getServerClient(), { redirectTo: "/dashboard" });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
/** The session cookie name shared by every Buildspace app. */
|
|
23
|
+
declare const SESSION_COOKIE_NAME = "bs_session";
|
|
24
|
+
/** The minimal server-client surface the adapter needs (a `Buildspace` instance). */
|
|
25
|
+
interface AuthServerClient {
|
|
26
|
+
auth: {
|
|
27
|
+
getSession(sessionToken: string): Promise<AuthSession | null>;
|
|
28
|
+
handleCallback(request: Request | URL | string, opts?: {
|
|
29
|
+
redirectUri?: string;
|
|
30
|
+
}): Promise<TokenResponse>;
|
|
31
|
+
signOut(sessionToken?: string): Promise<void>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Options controlling the `bs_session` cookie attributes. */
|
|
35
|
+
interface SessionCookieOptions {
|
|
36
|
+
/** Cookie domain. Omitted by default (host-only cookie). */
|
|
37
|
+
domain?: string;
|
|
38
|
+
/** Cookie path. Defaults to `/`. */
|
|
39
|
+
path?: string;
|
|
40
|
+
/** SameSite attribute. Defaults to `Lax`. */
|
|
41
|
+
sameSite?: "lax" | "strict" | "none";
|
|
42
|
+
/** Set the `Secure` attribute. Defaults to `true` outside development. */
|
|
43
|
+
secure?: boolean;
|
|
44
|
+
}
|
|
45
|
+
/** Build a `Set-Cookie` header value that stores the session token. */
|
|
46
|
+
declare function buildSessionCookie(token: string, maxAgeSeconds: number, opts?: SessionCookieOptions): string;
|
|
47
|
+
/** Build a `Set-Cookie` header value that clears the session cookie. */
|
|
48
|
+
declare function buildClearSessionCookie(opts?: SessionCookieOptions): string;
|
|
49
|
+
/**
|
|
50
|
+
* Anything the adapter can read the session cookie from: a web `Request`,
|
|
51
|
+
* or a cookie store with a `get(name)` method (e.g. the object returned by
|
|
52
|
+
* Next.js `cookies()` in Server Components and Route Handlers).
|
|
53
|
+
*/
|
|
54
|
+
type SessionCookieSource = Request | {
|
|
55
|
+
get(name: string): {
|
|
56
|
+
value: string;
|
|
57
|
+
} | string | null | undefined;
|
|
58
|
+
};
|
|
59
|
+
/** Read the raw session token from a request or cookie store, or `null`. */
|
|
60
|
+
declare function getSessionToken(source: SessionCookieSource): string | null;
|
|
61
|
+
/** An {@link AuthSession} plus the raw token it was resolved from. */
|
|
62
|
+
type SessionWithToken = AuthSession & {
|
|
63
|
+
token: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Cookie-aware session lookup.
|
|
67
|
+
*
|
|
68
|
+
* Reads the `bs_session` cookie from the given source and verifies it with
|
|
69
|
+
* the Buildspace API. Returns `null` when there is no cookie or the token
|
|
70
|
+
* is expired/revoked. Network/5xx errors also resolve to `null` so a blip
|
|
71
|
+
* never crashes rendering — sign-in state degrades to "signed out".
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* // Server Component
|
|
76
|
+
* import { cookies } from "next/headers";
|
|
77
|
+
* const session = await getSession(getServerClient(), await cookies());
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
declare function getSession(client: AuthServerClient, source: SessionCookieSource): Promise<SessionWithToken | null>;
|
|
81
|
+
/**
|
|
82
|
+
* Like {@link getSession} but throws a `BuildspaceError` (401) when there is
|
|
83
|
+
* no valid session. Use in route handlers and server actions that must only
|
|
84
|
+
* run for signed-in users.
|
|
85
|
+
*/
|
|
86
|
+
declare function requireSession(client: AuthServerClient, source: SessionCookieSource): Promise<SessionWithToken>;
|
|
87
|
+
/** Options for {@link createAuthCallback}. */
|
|
88
|
+
interface CreateAuthCallbackOptions {
|
|
89
|
+
/** Cookie attribute overrides. */
|
|
90
|
+
cookie?: SessionCookieOptions;
|
|
91
|
+
/**
|
|
92
|
+
* Called when the code exchange fails. Return a `Response` to control the
|
|
93
|
+
* error page; by default the error is rethrown (surfacing your framework's
|
|
94
|
+
* error handling).
|
|
95
|
+
*/
|
|
96
|
+
onError?: (error: unknown, request: Request) => Response | Promise<Response>;
|
|
97
|
+
/**
|
|
98
|
+
* Signup/sign-in side effects (mirror the user into your DB, send a
|
|
99
|
+
* welcome email, track an event). Failures are logged and never break
|
|
100
|
+
* login.
|
|
101
|
+
*/
|
|
102
|
+
onSignIn?: (ctx: {
|
|
103
|
+
accessToken: string;
|
|
104
|
+
request: Request;
|
|
105
|
+
user: AuthUser;
|
|
106
|
+
}) => void | Promise<void>;
|
|
107
|
+
/** Where to send the user after login. Defaults to `/`. */
|
|
108
|
+
redirectTo?: string;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Create the OAuth callback route handler.
|
|
112
|
+
*
|
|
113
|
+
* Exchanges the `?code=` for tokens, runs your `onSignIn` hook, stores the
|
|
114
|
+
* access token in the `bs_session` cookie (with `expires_in` as `Max-Age`),
|
|
115
|
+
* and redirects to `redirectTo`.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* // app/api/auth/callback/route.ts
|
|
120
|
+
* export const GET = createAuthCallback(getServerClient(), {
|
|
121
|
+
* redirectTo: "/dashboard",
|
|
122
|
+
* onSignIn: async ({ user }) => upsertUser(user),
|
|
123
|
+
* });
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
declare function createAuthCallback(client: AuthServerClient, options?: CreateAuthCallbackOptions): (request: Request) => Promise<Response>;
|
|
127
|
+
/**
|
|
128
|
+
* Create the logout route handler (`POST /api/auth/logout`).
|
|
129
|
+
*
|
|
130
|
+
* Revokes the session with the Buildspace API (already-expired sessions are
|
|
131
|
+
* ignored) and clears the `bs_session` cookie.
|
|
132
|
+
*/
|
|
133
|
+
declare function createLogoutRoute(client: AuthServerClient, options?: {
|
|
134
|
+
cookie?: SessionCookieOptions;
|
|
135
|
+
}): (request: Request) => Promise<Response>;
|
|
136
|
+
/**
|
|
137
|
+
* Create the session route handler (`GET /api/auth/session`).
|
|
138
|
+
*
|
|
139
|
+
* Returns `{ session }` for the current cookie, with the raw token omitted —
|
|
140
|
+
* this response is safe to expose to the browser.
|
|
141
|
+
*/
|
|
142
|
+
declare function createSessionRoute(client: AuthServerClient): (request: Request) => Promise<Response>;
|
|
143
|
+
/**
|
|
144
|
+
* Middleware helper: redirect requests that don't carry a session cookie.
|
|
145
|
+
*
|
|
146
|
+
* This is a fast presence check (no API call — middleware runs on every
|
|
147
|
+
* matched request); route handlers and pages must still verify the session
|
|
148
|
+
* with {@link getSession}.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```ts
|
|
152
|
+
* // middleware.ts / proxy.ts
|
|
153
|
+
* import { createSessionCookieGuard } from "@buildspacestudio/sdk/next";
|
|
154
|
+
*
|
|
155
|
+
* export const proxy = createSessionCookieGuard({ redirectTo: "/" });
|
|
156
|
+
* export const config = { matcher: ["/dashboard/:path*"] };
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
declare function createSessionCookieGuard(options?: {
|
|
160
|
+
/** Where to send signed-out users. Defaults to `/`. */
|
|
161
|
+
redirectTo?: string;
|
|
162
|
+
}): (request: Request) => Response | undefined;
|
|
163
|
+
|
|
164
|
+
export { type AuthServerClient, type CreateAuthCallbackOptions, SESSION_COOKIE_NAME, type SessionCookieOptions, type SessionCookieSource, type SessionWithToken, buildClearSessionCookie, buildSessionCookie, createAuthCallback, createLogoutRoute, createSessionCookieGuard, createSessionRoute, getSession, getSessionToken, requireSession };
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { a as AuthSession, T as TokenResponse, b as AuthUser } from '../server-Suq3tZZC.js';
|
|
2
|
+
import '../http-D2gXpNpr.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Framework adapter for Next.js (and any framework using web-standard
|
|
6
|
+
* `Request`/`Response` route handlers).
|
|
7
|
+
*
|
|
8
|
+
* Replaces the auth glue every creator app used to hand-roll: the OAuth
|
|
9
|
+
* callback route, logout + session routes, a cookie-aware `getSession()`,
|
|
10
|
+
* and a middleware cookie guard — all standardized on the `bs_session`
|
|
11
|
+
* cookie.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* // app/api/auth/callback/route.ts
|
|
16
|
+
* import { createAuthCallback } from "@buildspacestudio/sdk/next";
|
|
17
|
+
* import { getServerClient } from "@/lib/buildspace";
|
|
18
|
+
*
|
|
19
|
+
* export const GET = createAuthCallback(getServerClient(), { redirectTo: "/dashboard" });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
/** The session cookie name shared by every Buildspace app. */
|
|
23
|
+
declare const SESSION_COOKIE_NAME = "bs_session";
|
|
24
|
+
/** The minimal server-client surface the adapter needs (a `Buildspace` instance). */
|
|
25
|
+
interface AuthServerClient {
|
|
26
|
+
auth: {
|
|
27
|
+
getSession(sessionToken: string): Promise<AuthSession | null>;
|
|
28
|
+
handleCallback(request: Request | URL | string, opts?: {
|
|
29
|
+
redirectUri?: string;
|
|
30
|
+
}): Promise<TokenResponse>;
|
|
31
|
+
signOut(sessionToken?: string): Promise<void>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Options controlling the `bs_session` cookie attributes. */
|
|
35
|
+
interface SessionCookieOptions {
|
|
36
|
+
/** Cookie domain. Omitted by default (host-only cookie). */
|
|
37
|
+
domain?: string;
|
|
38
|
+
/** Cookie path. Defaults to `/`. */
|
|
39
|
+
path?: string;
|
|
40
|
+
/** SameSite attribute. Defaults to `Lax`. */
|
|
41
|
+
sameSite?: "lax" | "strict" | "none";
|
|
42
|
+
/** Set the `Secure` attribute. Defaults to `true` outside development. */
|
|
43
|
+
secure?: boolean;
|
|
44
|
+
}
|
|
45
|
+
/** Build a `Set-Cookie` header value that stores the session token. */
|
|
46
|
+
declare function buildSessionCookie(token: string, maxAgeSeconds: number, opts?: SessionCookieOptions): string;
|
|
47
|
+
/** Build a `Set-Cookie` header value that clears the session cookie. */
|
|
48
|
+
declare function buildClearSessionCookie(opts?: SessionCookieOptions): string;
|
|
49
|
+
/**
|
|
50
|
+
* Anything the adapter can read the session cookie from: a web `Request`,
|
|
51
|
+
* or a cookie store with a `get(name)` method (e.g. the object returned by
|
|
52
|
+
* Next.js `cookies()` in Server Components and Route Handlers).
|
|
53
|
+
*/
|
|
54
|
+
type SessionCookieSource = Request | {
|
|
55
|
+
get(name: string): {
|
|
56
|
+
value: string;
|
|
57
|
+
} | string | null | undefined;
|
|
58
|
+
};
|
|
59
|
+
/** Read the raw session token from a request or cookie store, or `null`. */
|
|
60
|
+
declare function getSessionToken(source: SessionCookieSource): string | null;
|
|
61
|
+
/** An {@link AuthSession} plus the raw token it was resolved from. */
|
|
62
|
+
type SessionWithToken = AuthSession & {
|
|
63
|
+
token: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Cookie-aware session lookup.
|
|
67
|
+
*
|
|
68
|
+
* Reads the `bs_session` cookie from the given source and verifies it with
|
|
69
|
+
* the Buildspace API. Returns `null` when there is no cookie or the token
|
|
70
|
+
* is expired/revoked. Network/5xx errors also resolve to `null` so a blip
|
|
71
|
+
* never crashes rendering — sign-in state degrades to "signed out".
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* // Server Component
|
|
76
|
+
* import { cookies } from "next/headers";
|
|
77
|
+
* const session = await getSession(getServerClient(), await cookies());
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
declare function getSession(client: AuthServerClient, source: SessionCookieSource): Promise<SessionWithToken | null>;
|
|
81
|
+
/**
|
|
82
|
+
* Like {@link getSession} but throws a `BuildspaceError` (401) when there is
|
|
83
|
+
* no valid session. Use in route handlers and server actions that must only
|
|
84
|
+
* run for signed-in users.
|
|
85
|
+
*/
|
|
86
|
+
declare function requireSession(client: AuthServerClient, source: SessionCookieSource): Promise<SessionWithToken>;
|
|
87
|
+
/** Options for {@link createAuthCallback}. */
|
|
88
|
+
interface CreateAuthCallbackOptions {
|
|
89
|
+
/** Cookie attribute overrides. */
|
|
90
|
+
cookie?: SessionCookieOptions;
|
|
91
|
+
/**
|
|
92
|
+
* Called when the code exchange fails. Return a `Response` to control the
|
|
93
|
+
* error page; by default the error is rethrown (surfacing your framework's
|
|
94
|
+
* error handling).
|
|
95
|
+
*/
|
|
96
|
+
onError?: (error: unknown, request: Request) => Response | Promise<Response>;
|
|
97
|
+
/**
|
|
98
|
+
* Signup/sign-in side effects (mirror the user into your DB, send a
|
|
99
|
+
* welcome email, track an event). Failures are logged and never break
|
|
100
|
+
* login.
|
|
101
|
+
*/
|
|
102
|
+
onSignIn?: (ctx: {
|
|
103
|
+
accessToken: string;
|
|
104
|
+
request: Request;
|
|
105
|
+
user: AuthUser;
|
|
106
|
+
}) => void | Promise<void>;
|
|
107
|
+
/** Where to send the user after login. Defaults to `/`. */
|
|
108
|
+
redirectTo?: string;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Create the OAuth callback route handler.
|
|
112
|
+
*
|
|
113
|
+
* Exchanges the `?code=` for tokens, runs your `onSignIn` hook, stores the
|
|
114
|
+
* access token in the `bs_session` cookie (with `expires_in` as `Max-Age`),
|
|
115
|
+
* and redirects to `redirectTo`.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* // app/api/auth/callback/route.ts
|
|
120
|
+
* export const GET = createAuthCallback(getServerClient(), {
|
|
121
|
+
* redirectTo: "/dashboard",
|
|
122
|
+
* onSignIn: async ({ user }) => upsertUser(user),
|
|
123
|
+
* });
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
declare function createAuthCallback(client: AuthServerClient, options?: CreateAuthCallbackOptions): (request: Request) => Promise<Response>;
|
|
127
|
+
/**
|
|
128
|
+
* Create the logout route handler (`POST /api/auth/logout`).
|
|
129
|
+
*
|
|
130
|
+
* Revokes the session with the Buildspace API (already-expired sessions are
|
|
131
|
+
* ignored) and clears the `bs_session` cookie.
|
|
132
|
+
*/
|
|
133
|
+
declare function createLogoutRoute(client: AuthServerClient, options?: {
|
|
134
|
+
cookie?: SessionCookieOptions;
|
|
135
|
+
}): (request: Request) => Promise<Response>;
|
|
136
|
+
/**
|
|
137
|
+
* Create the session route handler (`GET /api/auth/session`).
|
|
138
|
+
*
|
|
139
|
+
* Returns `{ session }` for the current cookie, with the raw token omitted —
|
|
140
|
+
* this response is safe to expose to the browser.
|
|
141
|
+
*/
|
|
142
|
+
declare function createSessionRoute(client: AuthServerClient): (request: Request) => Promise<Response>;
|
|
143
|
+
/**
|
|
144
|
+
* Middleware helper: redirect requests that don't carry a session cookie.
|
|
145
|
+
*
|
|
146
|
+
* This is a fast presence check (no API call — middleware runs on every
|
|
147
|
+
* matched request); route handlers and pages must still verify the session
|
|
148
|
+
* with {@link getSession}.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```ts
|
|
152
|
+
* // middleware.ts / proxy.ts
|
|
153
|
+
* import { createSessionCookieGuard } from "@buildspacestudio/sdk/next";
|
|
154
|
+
*
|
|
155
|
+
* export const proxy = createSessionCookieGuard({ redirectTo: "/" });
|
|
156
|
+
* export const config = { matcher: ["/dashboard/:path*"] };
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
declare function createSessionCookieGuard(options?: {
|
|
160
|
+
/** Where to send signed-out users. Defaults to `/`. */
|
|
161
|
+
redirectTo?: string;
|
|
162
|
+
}): (request: Request) => Response | undefined;
|
|
163
|
+
|
|
164
|
+
export { type AuthServerClient, type CreateAuthCallbackOptions, SESSION_COOKIE_NAME, type SessionCookieOptions, type SessionCookieSource, type SessionWithToken, buildClearSessionCookie, buildSessionCookie, createAuthCallback, createLogoutRoute, createSessionCookieGuard, createSessionRoute, getSession, getSessionToken, requireSession };
|