@dashai/sdk 0.7.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/LICENSE +21 -0
- package/README.md +377 -0
- package/dist/auth/client.cjs +185 -0
- package/dist/auth/client.cjs.map +1 -0
- package/dist/auth/client.d.cts +137 -0
- package/dist/auth/client.d.ts +137 -0
- package/dist/auth/client.js +175 -0
- package/dist/auth/client.js.map +1 -0
- package/dist/auth/middleware.cjs +352 -0
- package/dist/auth/middleware.cjs.map +1 -0
- package/dist/auth/middleware.d.cts +90 -0
- package/dist/auth/middleware.d.ts +90 -0
- package/dist/auth/middleware.js +343 -0
- package/dist/auth/middleware.js.map +1 -0
- package/dist/auth/server.cjs +445 -0
- package/dist/auth/server.cjs.map +1 -0
- package/dist/auth/server.d.cts +170 -0
- package/dist/auth/server.d.ts +170 -0
- package/dist/auth/server.js +432 -0
- package/dist/auth/server.js.map +1 -0
- package/dist/auth/types.cjs +31 -0
- package/dist/auth/types.cjs.map +1 -0
- package/dist/auth/types.d.cts +163 -0
- package/dist/auth/types.d.ts +163 -0
- package/dist/auth/types.js +29 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/deps/index.cjs +117 -0
- package/dist/deps/index.cjs.map +1 -0
- package/dist/deps/index.d.cts +93 -0
- package/dist/deps/index.d.ts +93 -0
- package/dist/deps/index.js +112 -0
- package/dist/deps/index.js.map +1 -0
- package/dist/errors-BV75u7b9.d.cts +207 -0
- package/dist/errors-BV75u7b9.d.ts +207 -0
- package/dist/index.cjs +721 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +171 -0
- package/dist/index.d.ts +171 -0
- package/dist/index.js +703 -0
- package/dist/index.js.map +1 -0
- package/dist/query/index.cjs +621 -0
- package/dist/query/index.cjs.map +1 -0
- package/dist/query/index.d.cts +800 -0
- package/dist/query/index.d.ts +800 -0
- package/dist/query/index.js +617 -0
- package/dist/query/index.js.map +1 -0
- package/dist/react/index.cjs +199 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +117 -0
- package/dist/react/index.d.ts +117 -0
- package/dist/react/index.js +195 -0
- package/dist/react/index.js.map +1 -0
- package/dist/types-BLNQ1S1C.d.cts +396 -0
- package/dist/types-BLNQ1S1C.d.ts +396 -0
- package/package.json +109 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
// src/data/errors.ts
|
|
2
|
+
var DashwiseError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
retriable;
|
|
6
|
+
context;
|
|
7
|
+
/**
|
|
8
|
+
* Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).
|
|
9
|
+
* Mirrors the `x-request-id` response header. Populated whenever
|
|
10
|
+
* the backend's `RuntimeQueryController` (or any future endpoint
|
|
11
|
+
* that echoes the header) is the origin of this error. `null` when
|
|
12
|
+
* the failure is client-side (NetworkError / TimeoutError — the
|
|
13
|
+
* request never reached the server, so there's no server-issued
|
|
14
|
+
* ID to surface).
|
|
15
|
+
*
|
|
16
|
+
* Use this as a debugging trace anchor when filing a bug against a
|
|
17
|
+
* specific failed query — the matching row in `module_query_log`
|
|
18
|
+
* carries the full backend context (ast_hash, error_code,
|
|
19
|
+
* duration_ms, etc.).
|
|
20
|
+
*/
|
|
21
|
+
requestId;
|
|
22
|
+
constructor(code, message, options = {}) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = this.constructor.name;
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.status = options.status ?? 0;
|
|
27
|
+
this.retriable = options.retriable ?? false;
|
|
28
|
+
this.context = options.context;
|
|
29
|
+
this.requestId = options.requestId ?? null;
|
|
30
|
+
if (options.cause !== void 0) {
|
|
31
|
+
this.cause = options.cause;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// src/auth/config.ts
|
|
37
|
+
var DEFAULT_COOKIE_NAME = "dashwise.session";
|
|
38
|
+
function trimBase(url) {
|
|
39
|
+
return url.replace(/\/+$/, "");
|
|
40
|
+
}
|
|
41
|
+
function readEnv(key) {
|
|
42
|
+
if (typeof process === "undefined" || !process.env) return void 0;
|
|
43
|
+
const v = process.env[key];
|
|
44
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
45
|
+
}
|
|
46
|
+
function resolveFetch(custom) {
|
|
47
|
+
if (custom) return custom;
|
|
48
|
+
if (typeof globalThis.fetch !== "function") {
|
|
49
|
+
throw new Error(
|
|
50
|
+
"@dashai/sdk/auth: no `fetch` available. On Node < 18, pass an explicit `fetch` in the auth options."
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
return globalThis.fetch.bind(globalThis);
|
|
54
|
+
}
|
|
55
|
+
function resolveAuthOptions(options = {}) {
|
|
56
|
+
const apiBaseUrl = options.apiBaseUrl ?? readEnv("DASHWISE_API_URL");
|
|
57
|
+
if (!apiBaseUrl) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
"@dashai/sdk/auth: missing `apiBaseUrl`. Set it via the options arg or the DASHWISE_API_URL env var."
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const authBaseUrl = options.authBaseUrl ?? readEnv("DASHWISE_AUTH_URL") ?? apiBaseUrl;
|
|
63
|
+
const cookieName = options.cookieName ?? readEnv("DASHWISE_SESSION_COOKIE_NAME") ?? DEFAULT_COOKIE_NAME;
|
|
64
|
+
return {
|
|
65
|
+
apiBaseUrl: trimBase(apiBaseUrl),
|
|
66
|
+
authBaseUrl: trimBase(authBaseUrl),
|
|
67
|
+
cookieName,
|
|
68
|
+
fetch: resolveFetch(options.fetch)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/auth/types.ts
|
|
73
|
+
var AuthErrorCode = {
|
|
74
|
+
/** Backend rejected the exchange code (expired / replay / forged). */
|
|
75
|
+
INVALID_EXCHANGE_CODE: "INVALID_EXCHANGE_CODE",
|
|
76
|
+
/** Backend returned an unexpected response. */
|
|
77
|
+
PROTOCOL_ERROR: "PROTOCOL_ERROR",
|
|
78
|
+
/**
|
|
79
|
+
* `requirePermission(...)` / `requireRole(...)` rejected because
|
|
80
|
+
* the current session lacks the requested permission/role (P12.4).
|
|
81
|
+
* Includes the requested key in the error's `context`.
|
|
82
|
+
*/
|
|
83
|
+
PERMISSION_DENIED: "PERMISSION_DENIED",
|
|
84
|
+
/**
|
|
85
|
+
* `requirePermission(...)` / `requireRole(...)` was called from a
|
|
86
|
+
* context without RBAC info — usually because the session has no
|
|
87
|
+
* `installationId` (the user isn't inside an installed module),
|
|
88
|
+
* or the `/rbac/me` fetch failed silently. Callers in this state
|
|
89
|
+
* should fall back to anon UI or surface a missing-context error.
|
|
90
|
+
*/
|
|
91
|
+
RBAC_UNAVAILABLE: "RBAC_UNAVAILABLE"
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// src/auth/rbac.ts
|
|
95
|
+
function permissionGranted(rbac, key) {
|
|
96
|
+
if (!rbac || !rbac.permissions) return false;
|
|
97
|
+
return matchKey(rbac.permissions, key);
|
|
98
|
+
}
|
|
99
|
+
function roleGranted(rbac, roleKey) {
|
|
100
|
+
if (!rbac || !rbac.roles) return false;
|
|
101
|
+
return matchKey(rbac.roles, roleKey);
|
|
102
|
+
}
|
|
103
|
+
function anyPermissionGranted(rbac, keys) {
|
|
104
|
+
return keys.some((k) => permissionGranted(rbac, k));
|
|
105
|
+
}
|
|
106
|
+
function allPermissionsGranted(rbac, keys) {
|
|
107
|
+
return keys.every((k) => permissionGranted(rbac, k));
|
|
108
|
+
}
|
|
109
|
+
function rbacOf(session) {
|
|
110
|
+
if (!session) return null;
|
|
111
|
+
return {
|
|
112
|
+
roles: session.rbacRoles ?? [],
|
|
113
|
+
permissions: session.rbacPermissions ?? []
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function matchKey(stored, queryKey) {
|
|
117
|
+
if (stored.length === 0) return false;
|
|
118
|
+
for (const s of stored) {
|
|
119
|
+
if (s === queryKey) return true;
|
|
120
|
+
if (s.endsWith(":" + queryKey)) return true;
|
|
121
|
+
}
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/auth/server.ts
|
|
126
|
+
async function readSessionCookie(cookieName) {
|
|
127
|
+
try {
|
|
128
|
+
const mod = await import('next/headers').catch(() => null);
|
|
129
|
+
if (!mod) return null;
|
|
130
|
+
const cookieStore = await mod.cookies();
|
|
131
|
+
const cookie = cookieStore.get(cookieName);
|
|
132
|
+
return cookie?.value ?? null;
|
|
133
|
+
} catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
async function writeSessionCookie(cookieName, value, maxAgeSeconds) {
|
|
138
|
+
try {
|
|
139
|
+
const mod = await import('next/headers').catch(() => null);
|
|
140
|
+
if (!mod) return;
|
|
141
|
+
const cookieStore = await mod.cookies();
|
|
142
|
+
cookieStore.set(cookieName, value, {
|
|
143
|
+
httpOnly: true,
|
|
144
|
+
secure: true,
|
|
145
|
+
sameSite: "lax",
|
|
146
|
+
path: "/",
|
|
147
|
+
maxAge: maxAgeSeconds
|
|
148
|
+
});
|
|
149
|
+
} catch {
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async function clearSessionCookie(cookieName) {
|
|
153
|
+
try {
|
|
154
|
+
const mod = await import('next/headers').catch(() => null);
|
|
155
|
+
if (!mod) return;
|
|
156
|
+
const cookieStore = await mod.cookies();
|
|
157
|
+
cookieStore.set(cookieName, "", {
|
|
158
|
+
httpOnly: true,
|
|
159
|
+
secure: true,
|
|
160
|
+
sameSite: "lax",
|
|
161
|
+
path: "/",
|
|
162
|
+
maxAge: 0
|
|
163
|
+
});
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function parseSession(raw) {
|
|
168
|
+
if (!raw || typeof raw !== "object") return null;
|
|
169
|
+
const r = raw;
|
|
170
|
+
if (!r.user || typeof r.user.id !== "number" || typeof r.user.email !== "string") {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const role = r.role;
|
|
174
|
+
if (role !== "admin" && role !== "editor" && role !== "viewer") {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
const workspaceId = r.workspaceId ?? r.workspace_id;
|
|
178
|
+
if (typeof workspaceId !== "number") return null;
|
|
179
|
+
const expiresAt = r.expiresAt ?? r.expires_at;
|
|
180
|
+
if (typeof expiresAt !== "number") return null;
|
|
181
|
+
const installationId = r.installationId ?? r.installation_id;
|
|
182
|
+
const moduleId = r.moduleId ?? r.module_id;
|
|
183
|
+
const moduleSlug = r.moduleSlug ?? r.module_slug;
|
|
184
|
+
return {
|
|
185
|
+
user: {
|
|
186
|
+
id: r.user.id,
|
|
187
|
+
email: r.user.email,
|
|
188
|
+
name: r.user.name ?? null
|
|
189
|
+
},
|
|
190
|
+
workspaceId,
|
|
191
|
+
role,
|
|
192
|
+
...typeof installationId === "number" ? { installationId } : {},
|
|
193
|
+
...typeof moduleId === "number" ? { moduleId } : {},
|
|
194
|
+
...typeof moduleSlug === "string" ? { moduleSlug } : {},
|
|
195
|
+
expiresAt
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
async function getServerSession(options = {}) {
|
|
199
|
+
const cfg = resolveAuthOptions(options);
|
|
200
|
+
const cookieValue = await readSessionCookie(cfg.cookieName);
|
|
201
|
+
if (!cookieValue) return null;
|
|
202
|
+
const cookieHeader = `${cfg.cookieName}=${encodeURIComponent(cookieValue)}`;
|
|
203
|
+
const sessionUrl = `${cfg.apiBaseUrl}/api/auth/sessions/me`;
|
|
204
|
+
let sessionRes;
|
|
205
|
+
try {
|
|
206
|
+
sessionRes = await cfg.fetch(sessionUrl, {
|
|
207
|
+
method: "GET",
|
|
208
|
+
headers: {
|
|
209
|
+
Cookie: cookieHeader,
|
|
210
|
+
Accept: "application/json"
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
if (!sessionRes.ok) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
const sessionBody = await sessionRes.json().catch(() => null);
|
|
220
|
+
const session = parseSession(sessionBody);
|
|
221
|
+
if (!session) return null;
|
|
222
|
+
if (session.installationId !== void 0) {
|
|
223
|
+
const rbac = await fetchRbacMe(
|
|
224
|
+
cfg.apiBaseUrl,
|
|
225
|
+
cookieHeader,
|
|
226
|
+
session.installationId,
|
|
227
|
+
cfg.fetch
|
|
228
|
+
);
|
|
229
|
+
if (rbac) {
|
|
230
|
+
session.rbacRoles = rbac.roles;
|
|
231
|
+
session.rbacPermissions = rbac.permissions;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return session;
|
|
235
|
+
}
|
|
236
|
+
async function fetchRbacMe(apiBaseUrl, cookieHeader, installationId, fetchImpl) {
|
|
237
|
+
const url = `${apiBaseUrl}/api/installations/${installationId}/rbac/me`;
|
|
238
|
+
let res;
|
|
239
|
+
try {
|
|
240
|
+
res = await fetchImpl(url, {
|
|
241
|
+
method: "GET",
|
|
242
|
+
headers: {
|
|
243
|
+
Cookie: cookieHeader,
|
|
244
|
+
Accept: "application/json"
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
if (!res.ok) return null;
|
|
251
|
+
const body = await res.json().catch(() => null);
|
|
252
|
+
if (!body || typeof body !== "object") return null;
|
|
253
|
+
const rolesRaw = body.roles;
|
|
254
|
+
const permsRaw = body.permissions;
|
|
255
|
+
if (!Array.isArray(rolesRaw) || !Array.isArray(permsRaw)) return null;
|
|
256
|
+
return {
|
|
257
|
+
roles: rolesRaw.filter((r) => typeof r === "string"),
|
|
258
|
+
permissions: permsRaw.filter((p) => typeof p === "string")
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
async function exchangeCode(code, options = {}) {
|
|
262
|
+
const cfg = resolveAuthOptions(options);
|
|
263
|
+
const url = `${cfg.apiBaseUrl}/api/auth/sessions/exchange`;
|
|
264
|
+
let res;
|
|
265
|
+
try {
|
|
266
|
+
res = await cfg.fetch(url, {
|
|
267
|
+
method: "POST",
|
|
268
|
+
headers: {
|
|
269
|
+
"Content-Type": "application/json",
|
|
270
|
+
Accept: "application/json"
|
|
271
|
+
},
|
|
272
|
+
body: JSON.stringify({ code })
|
|
273
|
+
});
|
|
274
|
+
} catch (err) {
|
|
275
|
+
throw new DashwiseError(AuthErrorCode.PROTOCOL_ERROR, "Auth exchange request failed", {
|
|
276
|
+
cause: err
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
if (!res.ok) {
|
|
280
|
+
throw new DashwiseError(
|
|
281
|
+
AuthErrorCode.INVALID_EXCHANGE_CODE,
|
|
282
|
+
`Auth exchange rejected (HTTP ${res.status})`,
|
|
283
|
+
{ status: res.status }
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
const body = await res.json().catch(() => null);
|
|
287
|
+
if (!body) {
|
|
288
|
+
throw new DashwiseError(
|
|
289
|
+
AuthErrorCode.PROTOCOL_ERROR,
|
|
290
|
+
"Auth exchange returned an unparseable body"
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
const sessionToken = body.sessionToken ?? body.session_token;
|
|
294
|
+
const maxAgeSeconds = body.maxAgeSeconds ?? body.max_age_seconds;
|
|
295
|
+
const session = parseSession(body.session);
|
|
296
|
+
if (!sessionToken || typeof maxAgeSeconds !== "number" || !session) {
|
|
297
|
+
throw new DashwiseError(
|
|
298
|
+
AuthErrorCode.PROTOCOL_ERROR,
|
|
299
|
+
"Auth exchange returned an invalid envelope"
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
await writeSessionCookie(cfg.cookieName, sessionToken, maxAgeSeconds);
|
|
303
|
+
return { sessionToken, maxAgeSeconds, session };
|
|
304
|
+
}
|
|
305
|
+
async function signOut(options = {}) {
|
|
306
|
+
const cfg = resolveAuthOptions(options);
|
|
307
|
+
const cookieValue = await readSessionCookie(cfg.cookieName);
|
|
308
|
+
await clearSessionCookie(cfg.cookieName);
|
|
309
|
+
if (!cookieValue) return;
|
|
310
|
+
const url = `${cfg.apiBaseUrl}/api/auth/sessions/sign-out`;
|
|
311
|
+
try {
|
|
312
|
+
await cfg.fetch(url, {
|
|
313
|
+
method: "POST",
|
|
314
|
+
headers: {
|
|
315
|
+
Cookie: `${cfg.cookieName}=${encodeURIComponent(cookieValue)}`,
|
|
316
|
+
Accept: "application/json"
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
} catch {
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function hasPermissionInSession(session, permissionKey) {
|
|
323
|
+
return permissionGranted(rbacOf(session), permissionKey);
|
|
324
|
+
}
|
|
325
|
+
function hasRoleInSession(session, roleKey) {
|
|
326
|
+
return roleGranted(rbacOf(session), roleKey);
|
|
327
|
+
}
|
|
328
|
+
async function hasPermission(permissionKey, options = {}) {
|
|
329
|
+
const session = await getServerSession(options);
|
|
330
|
+
return hasPermissionInSession(session, permissionKey);
|
|
331
|
+
}
|
|
332
|
+
async function hasRole(roleKey, options = {}) {
|
|
333
|
+
const session = await getServerSession(options);
|
|
334
|
+
return hasRoleInSession(session, roleKey);
|
|
335
|
+
}
|
|
336
|
+
async function requirePermission(permissionKey, options = {}) {
|
|
337
|
+
const session = await getServerSession(options);
|
|
338
|
+
if (!session) {
|
|
339
|
+
throw new DashwiseError(
|
|
340
|
+
AuthErrorCode.RBAC_UNAVAILABLE,
|
|
341
|
+
`requirePermission('${permissionKey}'): no active session`,
|
|
342
|
+
{ status: 401, context: { permission: permissionKey } }
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
if (!hasPermissionInSession(session, permissionKey)) {
|
|
346
|
+
throw new DashwiseError(
|
|
347
|
+
AuthErrorCode.PERMISSION_DENIED,
|
|
348
|
+
`requirePermission('${permissionKey}'): denied`,
|
|
349
|
+
{
|
|
350
|
+
status: 403,
|
|
351
|
+
context: {
|
|
352
|
+
permission: permissionKey,
|
|
353
|
+
holds: session.rbacPermissions ?? []
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
return session;
|
|
359
|
+
}
|
|
360
|
+
async function requireAnyPermission(permissionKeys, options = {}) {
|
|
361
|
+
const session = await getServerSession(options);
|
|
362
|
+
if (!session) {
|
|
363
|
+
throw new DashwiseError(
|
|
364
|
+
AuthErrorCode.RBAC_UNAVAILABLE,
|
|
365
|
+
`requireAnyPermission([${permissionKeys.join(", ")}]): no active session`,
|
|
366
|
+
{ status: 401, context: { permissions: [...permissionKeys] } }
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
if (!anyPermissionGranted(rbacOf(session), permissionKeys)) {
|
|
370
|
+
throw new DashwiseError(
|
|
371
|
+
AuthErrorCode.PERMISSION_DENIED,
|
|
372
|
+
`requireAnyPermission([${permissionKeys.join(", ")}]): none granted`,
|
|
373
|
+
{
|
|
374
|
+
status: 403,
|
|
375
|
+
context: {
|
|
376
|
+
permissions: [...permissionKeys],
|
|
377
|
+
holds: session.rbacPermissions ?? []
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
return session;
|
|
383
|
+
}
|
|
384
|
+
async function requireAllPermissions(permissionKeys, options = {}) {
|
|
385
|
+
const session = await getServerSession(options);
|
|
386
|
+
if (!session) {
|
|
387
|
+
throw new DashwiseError(
|
|
388
|
+
AuthErrorCode.RBAC_UNAVAILABLE,
|
|
389
|
+
`requireAllPermissions([${permissionKeys.join(", ")}]): no active session`,
|
|
390
|
+
{ status: 401, context: { permissions: [...permissionKeys] } }
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
if (!allPermissionsGranted(rbacOf(session), permissionKeys)) {
|
|
394
|
+
throw new DashwiseError(
|
|
395
|
+
AuthErrorCode.PERMISSION_DENIED,
|
|
396
|
+
`requireAllPermissions([${permissionKeys.join(", ")}]): missing one or more`,
|
|
397
|
+
{
|
|
398
|
+
status: 403,
|
|
399
|
+
context: {
|
|
400
|
+
permissions: [...permissionKeys],
|
|
401
|
+
holds: session.rbacPermissions ?? []
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
return session;
|
|
407
|
+
}
|
|
408
|
+
async function requireRole(roleKey, options = {}) {
|
|
409
|
+
const session = await getServerSession(options);
|
|
410
|
+
if (!session) {
|
|
411
|
+
throw new DashwiseError(
|
|
412
|
+
AuthErrorCode.RBAC_UNAVAILABLE,
|
|
413
|
+
`requireRole('${roleKey}'): no active session`,
|
|
414
|
+
{ status: 401, context: { role: roleKey } }
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
if (!hasRoleInSession(session, roleKey)) {
|
|
418
|
+
throw new DashwiseError(
|
|
419
|
+
AuthErrorCode.PERMISSION_DENIED,
|
|
420
|
+
`requireRole('${roleKey}'): denied`,
|
|
421
|
+
{
|
|
422
|
+
status: 403,
|
|
423
|
+
context: { role: roleKey, holds: session.rbacRoles ?? [] }
|
|
424
|
+
}
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
return session;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export { exchangeCode, fetchRbacMe, getServerSession, hasPermission, hasPermissionInSession, hasRole, hasRoleInSession, requireAllPermissions, requireAnyPermission, requirePermission, requireRole, signOut };
|
|
431
|
+
//# sourceMappingURL=server.js.map
|
|
432
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/data/errors.ts","../../src/auth/config.ts","../../src/auth/types.ts","../../src/auth/rbac.ts","../../src/auth/server.ts"],"names":[],"mappings":";AAgGO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EAC9B,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA;AAAA;AAAA;AAAA;A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OAAO,OAAA,CAAQ,SAAA,IAAa,EAAC;AAAE;AAC3D,KACF;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"server.js","sourcesContent":["/**\n * Error model for @dashai/sdk.\n *\n * The backend speaks a structured error envelope:\n *\n * {\n * \"code\": \"ROW_NOT_FOUND\",\n * \"message\": \"Row 123 not found in tasks\",\n * \"retriable\": false,\n * \"context\": { ... }\n * }\n *\n * This module wraps that envelope in a typed `DashwiseError` plus a small\n * set of subclasses for the codes consumers most commonly want to branch\n * on (network errors, auth failures, row-not-found, contract violations).\n *\n * Anything not matched by a specific subclass becomes a plain\n * `DashwiseError` carrying the raw `code`. Branch on `.code` for codes\n * we don't have a class for; use `instanceof` for the common cases.\n */\n\n/**\n * Known error codes. Not exhaustive — the backend emits many codes\n * specific to individual modules / endpoints. Use these constants when\n * you want compile-time safety; otherwise treat `err.code` as a string.\n *\n * The list is curated to the codes a module author is most likely to\n * branch on. Adding a new code here is a non-breaking change.\n */\nexport const DashwiseErrorCode = {\n // Auth / authz\n UNAUTHENTICATED: 'UNAUTHENTICATED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INSTALLATION_NOT_FOUND: 'INSTALLATION_NOT_FOUND',\n INSTALLATION_MODE_UNSUPPORTED: 'INSTALLATION_MODE_UNSUPPORTED',\n // Contract enforcement\n CONTRACT_VIOLATION: 'CONTRACT_VIOLATION',\n FIELD_NOT_READABLE: 'FIELD_NOT_READABLE',\n FILTER_OP_UNKNOWN: 'FILTER_OP_UNKNOWN',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n // Cross-module dependencies (Phase 1 of the SDK query plane —\n // see dashwise-devops-docs/plans/modules-sdk-query-v1.md).\n // Surfaced when reading borrowed tables via `client.deps(slug)`.\n DEPENDENCY_NOT_DECLARED: 'DEPENDENCY_NOT_DECLARED',\n TABLE_NOT_IN_CONTRACT: 'TABLE_NOT_IN_CONTRACT',\n PROVIDER_TABLE_MISSING: 'PROVIDER_TABLE_MISSING',\n OPERATION_NOT_ALLOWED_BY_PROVIDER: 'OPERATION_NOT_ALLOWED_BY_PROVIDER',\n // Query-plane joins (Phase 3 — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p3-execution.md).\n // Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` can't\n // resolve the target. Pre-declared in slice 3.1 so slice 3.2's\n // backend translator can emit them through fromBackendEnvelope\n // without an SDK roundtrip.\n LINK_FIELD_NOT_FOUND: 'LINK_FIELD_NOT_FOUND',\n NOT_A_LINK_FIELD: 'NOT_A_LINK_FIELD',\n JOIN_NOT_LINKED: 'JOIN_NOT_LINKED',\n // Cross-module actions (Phase 7 slice 7.3a — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p7-cross-module-writes.md).\n // Surfaced when `qb.deps.<dep>.actions.<name>(input)` (generated\n // factory) dispatches against the new backend endpoint\n // `POST :installationId/deps/:providerSlug/actions/:actionName`.\n // Slice 7.2b ships the backend emitter; slice 7.3a (this slice)\n // reserves the codes + maps them to DepActionError in the SDK.\n ACTION_NOT_EXPOSED: 'ACTION_NOT_EXPOSED',\n ACTION_NOT_DECLARED: 'ACTION_NOT_DECLARED',\n ACTION_INPUT_INVALID: 'ACTION_INPUT_INVALID',\n ACTION_OUTPUT_INVALID: 'ACTION_OUTPUT_INVALID',\n ACTION_RATE_LIMITED: 'ACTION_RATE_LIMITED',\n ACTION_EXECUTION_FAILED: 'ACTION_EXECUTION_FAILED',\n // Data plane\n ROW_NOT_FOUND: 'ROW_NOT_FOUND',\n TABLE_NOT_FOUND: 'TABLE_NOT_FOUND',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n ROW_LIMIT_EXCEEDED: 'ROW_LIMIT_EXCEEDED',\n STORAGE_LIMIT_EXCEEDED: 'STORAGE_LIMIT_EXCEEDED',\n // Outbound / runtime\n OUTBOUND_NOT_ALLOWED: 'OUTBOUND_NOT_ALLOWED',\n OUTBOUND_CONCURRENCY_LIMITED: 'OUTBOUND_CONCURRENCY_LIMITED',\n // Transport\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n // Server\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type DashwiseErrorCode = (typeof DashwiseErrorCode)[keyof typeof DashwiseErrorCode];\n\n/**\n * Base class for every error thrown by @dashai/sdk. Carries the\n * structured envelope from the backend (or a synthetic one for\n * client-side failures like network errors / timeouts).\n *\n * Always thrown — never returned as a value. The async client methods\n * `.list()` / `.get()` etc. reject with one of these on failure.\n */\nexport class DashwiseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retriable: boolean;\n readonly context: Record<string, unknown> | undefined;\n /**\n * Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).\n * Mirrors the `x-request-id` response header. Populated whenever\n * the backend's `RuntimeQueryController` (or any future endpoint\n * that echoes the header) is the origin of this error. `null` when\n * the failure is client-side (NetworkError / TimeoutError — the\n * request never reached the server, so there's no server-issued\n * ID to surface).\n *\n * Use this as a debugging trace anchor when filing a bug against a\n * specific failed query — the matching row in `module_query_log`\n * carries the full backend context (ast_hash, error_code,\n * duration_ms, etc.).\n */\n readonly requestId: string | null;\n\n constructor(\n code: string,\n message: string,\n options: {\n status?: number;\n retriable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n /**\n * Phase 6 slice 6.2: backend `x-request-id` response header,\n * captured by the transport before throwing. Pass `undefined`\n * (or omit) for client-side errors that never hit the server.\n */\n requestId?: string | null;\n } = {},\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.status = options.status ?? 0;\n this.retriable = options.retriable ?? false;\n this.context = options.context;\n this.requestId = options.requestId ?? null;\n if (options.cause !== undefined) {\n // Node 18+ and modern browsers support Error.cause natively.\n // Use a property assignment because `super({ cause })` is awkward\n // when the base class only takes a string.\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n\n/** Network-level failure (DNS, connection refused, TLS, fetch threw). */\nexport class NetworkError extends DashwiseError {\n constructor(message: string, cause?: unknown) {\n super(DashwiseErrorCode.NETWORK_ERROR, message, { retriable: true, cause });\n }\n}\n\n/** Request exceeded the configured timeout (`timeoutMs`). */\nexport class TimeoutError extends DashwiseError {\n constructor(message: string, timeoutMs: number) {\n super(DashwiseErrorCode.TIMEOUT, message, {\n retriable: true,\n context: { timeout_ms: timeoutMs },\n });\n }\n}\n\n/** 401 — token missing/invalid. */\nexport class UnauthenticatedError extends DashwiseError {\n constructor(message = 'Authentication required', requestId: string | null = null) {\n super(DashwiseErrorCode.UNAUTHENTICATED, message, { status: 401, requestId });\n }\n}\n\n/** 403 — caller lacks the role/scope for this operation. */\nexport class ForbiddenError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.FORBIDDEN, message, { status: 403, context, requestId });\n }\n}\n\n/** 404 — `GET /db/<table>/<id>` for a missing or soft-deleted row. */\nexport class RowNotFoundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.ROW_NOT_FOUND, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * Schema-level rejection: dep contract violated, table not exposed, field\n * not readable, filter op not allowed. Covers the family of \"you asked for\n * something the manifest doesn't permit\" errors.\n */\nexport class ContractViolationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.CONTRACT_VIOLATION, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n/** 422-ish — request body failed validation. Inspect `context` for field-level errors. */\nexport class ValidationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.VALIDATION_FAILED, message, {\n status: 400,\n context,\n requestId,\n });\n }\n}\n\n// ── Cross-module dependency errors ─────────────────────────────────────\n//\n// Surfaced when calling `client.deps(slug).db<Row>(table).<op>(...)`.\n// Each subclass preserves the original backend `code` (unlike the older\n// `ContractViolationError` which collapses several codes onto a single\n// `CONTRACT_VIOLATION` string — that's a known wart we don't replicate\n// in new subclasses). Branch on `instanceof` for the common cases;\n// inspect `err.code` if you need to distinguish the two contract-error\n// codes (`DEPENDENCY_NOT_DECLARED` vs `TABLE_NOT_IN_CONTRACT`).\n\n/**\n * 404 — the caller's `module.json#dependencies` doesn't declare a\n * dependency on the requested provider module, OR the declared dep\n * exists but its `reads[]` block doesn't include the requested table.\n *\n * Either way the fix is on the **caller's** side: update the manifest\n * to declare the dep / add the table to `reads[]`, then re-publish.\n *\n * Covers both `DEPENDENCY_NOT_DECLARED` and `TABLE_NOT_IN_CONTRACT` —\n * inspect `err.code` to distinguish if you need different UX per case.\n */\nexport class DependencyContractError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * 404 — the provider's physical table no longer exists. This means the\n * provider published a version that dropped the table while the\n * consumer's installation still pinned the old contract. Recovery is\n * on the **provider's** side (republish with the table) or the\n * workspace admin's (downgrade the provider, or upgrade the consumer\n * to a version whose `dependencies[]` no longer references it).\n */\nexport class ProviderTableMissingError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.PROVIDER_TABLE_MISSING, message, {\n status: 404,\n context,\n requestId,\n });\n }\n}\n\n/**\n * 403 — the provider's `exposes.operations.<verb>.allowed` is explicitly\n * `false` for the requested verb. Distinct from `OPERATION_NOT_ALLOWED`\n * (which is the **owner's** own-table policy) — `OPERATION_NOT_ALLOWED_BY_PROVIDER`\n * is the provider opting out of letting depending modules use a verb.\n *\n * No caller-side fix; either the provider needs to flip the gate, or\n * the consumer needs to find a different way to satisfy the use case.\n */\nexport class OperationNotAllowedByProviderError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n// ── Join errors (Phase 3) ──────────────────────────────────────────────\n//\n// Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` on the\n// generated `qb` builder can't resolve the target against the\n// manifest. Pre-declared in slice 3.1; raised by the backend\n// translator in slice 3.2. Same one-subclass-with-preserved-code\n// pattern as DependencyContractError so authors can switch on\n// `err.code` for the three sub-cases:\n//\n// LINK_FIELD_NOT_FOUND `.join('xyz')` where `xyz` isn't a field\n// on the source table. Fix: pass an\n// explicit `on` argument, or correct the slug.\n//\n// NOT_A_LINK_FIELD `.join('title')` where `title` exists on\n// the source table but its type isn't\n// `link_row`. Fix: use a real link field,\n// or pass explicit `on`.\n//\n// JOIN_NOT_LINKED `.join('sibling_table')` where the target\n// is a sibling table but no link field\n// bridges them. Fix: pass explicit `on`.\n\n/**\n * 400 — `.join()` / `.leftJoin()` referenced a target the manifest\n * can't resolve. Covers the three sub-cases above; inspect\n * `err.code` to distinguish.\n *\n * Author-side fix in every case: either correct the slug, or pass\n * an explicit `on` argument to bypass link-field inference.\n */\nexport class JoinError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 400, context, requestId });\n }\n}\n\n// ── Cross-module action errors (Phase 7 slice 7.3a, 2026-05-20) ──────\n//\n// Surfaced by the codegen-emitted `qb.deps.<dep>.actions.<name>(input)`\n// factory when the backend's cross-module dispatch\n// (`CrossModuleActionService.dispatch()`) rejects. Six sub-cases all\n// covered by `DepActionError`; inspect `err.code` to discriminate.\n//\n// ACTION_NOT_EXPOSED 403 — provider's manifest doesn't expose\n// the action, OR visibility='private'.\n// Recovery: provider author needs to\n// publish a version that exposes it.\n// ACTION_NOT_DECLARED 403 — consumer's manifest doesn't list\n// the action in dependencies[].actions[].\n// Recovery: add it + republish.\n// ACTION_INPUT_INVALID 400 — input fails Ajv against the\n// provider's declared input schema.\n// Recovery: fix the call site (typical\n// with stale codegen + drift).\n// ACTION_OUTPUT_INVALID 500 — provider returned a value that fails\n// the declared output schema. This is a\n// PROVIDER-author bug; consumer can\n// only file an issue.\n// ACTION_RATE_LIMITED 429 — per-actor or per-caller-installation\n// rate limit exceeded. Retry with\n// backoff after Retry-After (slice 7.4).\n// ACTION_EXECUTION_FAILED 200-envelope — action body threw, timed out,\n// or OOM-ed. Provider-author bug;\n// trace surfaced in err.context.trace.\n\n/**\n * Single subclass for every cross-module action failure. The code\n * (and HTTP status) varies per sub-case; the wrapping class lets\n * consumers `catch (e) { if (e instanceof DepActionError) {...} }`\n * regardless of which sub-case fired.\n */\nexport class DepActionError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n status: number,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, {\n status,\n retriable: code === DashwiseErrorCode.ACTION_RATE_LIMITED,\n context,\n requestId,\n });\n }\n}\n\n// ── Factory: backend envelope → typed error ────────────────────────────\n\ninterface BackendErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\n/**\n * Build a typed `DashwiseError` from the backend's response envelope.\n *\n * The mapping picks the most specific subclass for codes we have a class\n * for; everything else becomes a plain `DashwiseError` carrying the raw\n * code. This keeps the type set small while still letting consumers\n * branch on string codes when they want to.\n *\n * Phase 6 slice 6.2 (2026-05-19): accepts an optional `requestId` —\n * the backend's `x-request-id` response header — and threads it onto\n * every produced error so consumers can use it as a debugging trace\n * anchor. Default `null` for backward compat; the transport always\n * passes it through.\n */\nexport function fromBackendEnvelope(\n status: number,\n envelope: BackendErrorEnvelope | null,\n requestId: string | null = null,\n): DashwiseError {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? `HTTP ${status}`;\n const context = envelope?.context;\n\n switch (code) {\n case DashwiseErrorCode.UNAUTHENTICATED:\n case DashwiseErrorCode.TOKEN_EXPIRED:\n return new UnauthenticatedError(message, requestId);\n case DashwiseErrorCode.FORBIDDEN:\n return new ForbiddenError(message, context, requestId);\n case DashwiseErrorCode.ROW_NOT_FOUND:\n return new RowNotFoundError(message, context, requestId);\n case DashwiseErrorCode.CONTRACT_VIOLATION:\n case DashwiseErrorCode.FIELD_NOT_READABLE:\n case DashwiseErrorCode.FILTER_OP_UNKNOWN:\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED:\n return new ContractViolationError(message, context, requestId);\n case DashwiseErrorCode.VALIDATION_FAILED:\n return new ValidationError(message, context, requestId);\n case DashwiseErrorCode.DEPENDENCY_NOT_DECLARED:\n case DashwiseErrorCode.TABLE_NOT_IN_CONTRACT:\n return new DependencyContractError(code, message, context, requestId);\n case DashwiseErrorCode.PROVIDER_TABLE_MISSING:\n return new ProviderTableMissingError(message, context, requestId);\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER:\n return new OperationNotAllowedByProviderError(message, context, requestId);\n case DashwiseErrorCode.LINK_FIELD_NOT_FOUND:\n case DashwiseErrorCode.NOT_A_LINK_FIELD:\n case DashwiseErrorCode.JOIN_NOT_LINKED:\n return new JoinError(code, message, context, requestId);\n case DashwiseErrorCode.ACTION_NOT_EXPOSED:\n case DashwiseErrorCode.ACTION_NOT_DECLARED:\n return new DepActionError(code, message, 403, context, requestId);\n case DashwiseErrorCode.ACTION_INPUT_INVALID:\n return new DepActionError(code, message, 400, context, requestId);\n case DashwiseErrorCode.ACTION_OUTPUT_INVALID:\n return new DepActionError(code, message, 500, context, requestId);\n case DashwiseErrorCode.ACTION_RATE_LIMITED:\n return new DepActionError(code, message, 429, context, requestId);\n case DashwiseErrorCode.ACTION_EXECUTION_FAILED:\n // ACTION_EXECUTION_FAILED arrives as a 200 envelope from the\n // backend (the host succeeded; the action body crashed). The\n // _callAction helper unwraps the envelope and synthesizes this\n // via the factory call — status 200 reflects \"the transport was\n // fine; the failure is in the application layer\".\n return new DepActionError(code, message, 200, context, requestId);\n default:\n return new DashwiseError(code, message, {\n status,\n retriable: envelope?.retriable ?? false,\n context,\n requestId,\n });\n }\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return DashwiseErrorCode.UNAUTHENTICATED;\n if (status === 403) return DashwiseErrorCode.FORBIDDEN;\n if (status === 404) return DashwiseErrorCode.ROW_NOT_FOUND;\n if (status >= 500) return DashwiseErrorCode.INTERNAL_ERROR;\n return 'HTTP_ERROR';\n}\n","/**\n * Internal config resolution for the auth layer.\n *\n * Reads runtime defaults from `process.env.DASHWISE_*` and applies\n * fallbacks. Every public auth function calls `resolveAuthOptions`\n * with its caller-supplied options so the call site can override\n * any field per-call.\n */\n\nimport type { AuthOptions } from './types.js';\n\nexport interface ResolvedAuthOptions {\n apiBaseUrl: string;\n authBaseUrl: string;\n cookieName: string;\n fetch: typeof globalThis.fetch;\n}\n\nconst DEFAULT_COOKIE_NAME = 'dashwise.session';\n\n/**\n * Strip trailing slashes from a base URL. Internal — call sites never\n * have to think about trailing slashes; just give us a URL.\n */\nfunction trimBase(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n\n/**\n * Read a string-typed env var with a fallback. Works in Node + edge +\n * browser builds (process is shimmed in the latter).\n */\nfunction readEnv(key: string): string | undefined {\n // Edge / browser builds may not have `process` at all — guard.\n if (typeof process === 'undefined' || !process.env) return undefined;\n const v = process.env[key];\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\n\nfunction resolveFetch(custom: typeof globalThis.fetch | undefined): typeof globalThis.fetch {\n if (custom) return custom;\n if (typeof globalThis.fetch !== 'function') {\n throw new Error(\n '@dashai/sdk/auth: no `fetch` available. On Node < 18, pass an explicit `fetch` in the auth options.',\n );\n }\n return globalThis.fetch.bind(globalThis);\n}\n\n/**\n * Resolve options to a fully-specified config. Throws if the\n * required base URLs are missing — auth can't function without\n * knowing where the backend is.\n */\nexport function resolveAuthOptions(options: AuthOptions = {}): ResolvedAuthOptions {\n const apiBaseUrl = options.apiBaseUrl ?? readEnv('DASHWISE_API_URL');\n if (!apiBaseUrl) {\n throw new Error(\n '@dashai/sdk/auth: missing `apiBaseUrl`. Set it via the options arg or the DASHWISE_API_URL env var.',\n );\n }\n\n // authBaseUrl falls back to apiBaseUrl. Most prod deployments will\n // run the main app + the API on different hosts (e.g.\n // app.dashwise.io vs api.dashwise.io); in dev / single-host setups\n // they're the same.\n const authBaseUrl = options.authBaseUrl ?? readEnv('DASHWISE_AUTH_URL') ?? apiBaseUrl;\n\n const cookieName =\n options.cookieName ?? readEnv('DASHWISE_SESSION_COOKIE_NAME') ?? DEFAULT_COOKIE_NAME;\n\n return {\n apiBaseUrl: trimBase(apiBaseUrl),\n authBaseUrl: trimBase(authBaseUrl),\n cookieName,\n fetch: resolveFetch(options.fetch),\n };\n}\n","/**\n * Public types for the @dashai/sdk/auth/* subpaths.\n *\n * The DashWise NestJS backend is the identity provider (IDP); these\n * types describe the SSO + session contract the SDK consumes. Changes\n * here are SemVer-significant — every Next.js module + custom-runtime\n * deployment depends on this shape.\n */\n\n/**\n * Workspace-scoped session for a logged-in user. Returned by\n * `getServerSession()` (server-side) and `useSession()` (client-side).\n *\n * `user` carries identity; `workspaceId` + `role` carry workspace\n * scoping; `installationId` + `moduleId` + `moduleSlug` carry\n * module-install context (present in custom-module runtimes and\n * post-install AI-builder previews; absent in pre-install /\n * marketplace / hand-author dev contexts).\n *\n * `expiresAt` is wall-clock ms (Unix epoch). The session is auto-\n * refreshed by the SDK middleware/server helpers while the user is\n * active; consumers shouldn't manually compare against `Date.now()`\n * unless they're displaying a countdown to the user.\n */\nexport interface Session {\n user: {\n id: number;\n email: string;\n /** Display name. Null if the user hasn't set one yet. */\n name: string | null;\n };\n workspaceId: number;\n role: 'admin' | 'editor' | 'viewer';\n installationId?: number;\n moduleId?: number;\n moduleSlug?: string;\n /** Wall-clock expiry, Unix ms. */\n expiresAt: number;\n /**\n * Module RBAC roles for the current installation (P12.4). Populated\n * by the SDK via a parallel `/api/installations/:id/rbac/me` fetch\n * when `installationId` is set. Values are NAMESPACED keys —\n * `<module_slug>:<role>` — to leave room for future cross-module\n * grants without breaking the shape.\n *\n * Empty array means the user has no role grants for this install\n * (denied to anything role-gated). `undefined` means the SDK\n * hasn't fetched the RBAC data yet (sessions outside an install\n * context, or transient pre-resolution state).\n */\n rbacRoles?: string[];\n\n /**\n * Module RBAC permissions for the current installation (P12.4).\n * Same shape + nullability semantics as `rbacRoles`. Values are\n * namespaced (`<module_slug>:<permission_key>`); the SDK's\n * `hasPermission` / `requirePermission` helpers accept either the\n * bare or the namespaced form.\n *\n * This is the resolved permission set — already expanded via\n * `includes` graph traversal on the backend — so client-side\n * checks are O(1) set-membership.\n */\n rbacPermissions?: string[];\n}\n\n/**\n * Response shape of `GET /api/installations/:id/rbac/me`. The SDK\n * fetches this in parallel with `/api/auth/sessions/me` when the\n * session has an `installationId`.\n *\n * Both arrays are NAMESPACED (`<module_slug>:<key>`) — the SDK's\n * permission/role helpers strip the namespace at lookup time so\n * authors write bare keys (`tasks:delete`, `editor`).\n */\nexport interface RbacMeResponse {\n roles: string[];\n permissions: string[];\n}\n\n/**\n * Status returned by `useSession()` on the client. `loading` is the\n * initial render before the session fetch resolves; SSR-friendly\n * apps may want to gate suspense or skeletons on this.\n */\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\n/**\n * Shared configuration accepted by every auth helper. All fields are\n * optional; defaults come from the runtime env (`DASHWISE_*`) or\n * sensible static fallbacks.\n *\n * Pass an explicit object to override per-call (useful for tests +\n * for runtimes that can't read env vars at request time).\n */\nexport interface AuthOptions {\n /**\n * Base URL for the DashWise backend API (e.g.\n * `https://api.dashwise.io`). Used for `/api/auth/sessions/me`,\n * `/api/auth/sessions/exchange`, etc. Defaults to\n * `process.env.DASHWISE_API_URL`.\n */\n apiBaseUrl?: string;\n\n /**\n * Base URL for the DashWise main app's SSO entry point (e.g.\n * `https://app.dashwise.io`). Used for the initial redirect from\n * module middleware. Defaults to `process.env.DASHWISE_AUTH_URL`,\n * falling back to `apiBaseUrl` with no path suffix.\n */\n authBaseUrl?: string;\n\n /**\n * Name of the session cookie. Defaults to\n * `process.env.DASHWISE_SESSION_COOKIE_NAME` or `'dashwise.session'`.\n * Cookie scope is configured by the backend on set; the SDK only\n * reads/clears it.\n */\n cookieName?: string;\n\n /**\n * Optional fetch override (testing / custom HTTP agent). Defaults\n * to `globalThis.fetch`.\n */\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Response shape from `POST /api/auth/sessions/exchange`. The\n * `session_token` is the opaque cookie value to set; the consumer\n * shouldn't decode or store it elsewhere.\n */\nexport interface ExchangeResult {\n /** Opaque session cookie value (JWT under the hood). */\n sessionToken: string;\n /** Cookie max-age in seconds (matches the JWT exp). */\n maxAgeSeconds: number;\n /** Already-decoded session — saves an immediate /me round-trip. */\n session: Session;\n}\n\n/**\n * Errors thrown by the auth layer. Mirrors the data-plane error model\n * (subclass of `DashwiseError`) so consumers can catch all SDK errors\n * uniformly.\n */\nexport const AuthErrorCode = {\n /** Cookie missing or invalid — caller should redirect to sign-in. */\n NO_SESSION: 'NO_SESSION',\n /** Backend rejected the exchange code (expired / replay / forged). */\n INVALID_EXCHANGE_CODE: 'INVALID_EXCHANGE_CODE',\n /** Backend rejected the session refresh (expired beyond refresh window). */\n REFRESH_FAILED: 'REFRESH_FAILED',\n /** Backend returned an unexpected response. */\n PROTOCOL_ERROR: 'PROTOCOL_ERROR',\n /**\n * `requirePermission(...)` / `requireRole(...)` rejected because\n * the current session lacks the requested permission/role (P12.4).\n * Includes the requested key in the error's `context`.\n */\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n /**\n * `requirePermission(...)` / `requireRole(...)` was called from a\n * context without RBAC info — usually because the session has no\n * `installationId` (the user isn't inside an installed module),\n * or the `/rbac/me` fetch failed silently. Callers in this state\n * should fall back to anon UI or surface a missing-context error.\n */\n RBAC_UNAVAILABLE: 'RBAC_UNAVAILABLE',\n} as const;\n\nexport type AuthErrorCode = (typeof AuthErrorCode)[keyof typeof AuthErrorCode];\n","/**\n * Module RBAC helpers — shared between server-side (`auth/server.ts`),\n * middleware (`auth/middleware.ts`), and client-side (`auth/client.tsx`).\n *\n * The design lives at\n * `dashwise-devops-docs/plans/module-rbac-design.md` (Locked\n * 2026-05-17). This file implements the **runtime-side resolution**\n * — the actual check against a resolved permission/role set.\n *\n * **Where the resolved set comes from** depends on the caller:\n * - Server-side: `getServerSession()` fetches `/api/installations/:id/rbac/me`\n * in parallel with `/api/auth/sessions/me` and merges into the\n * returned `Session`.\n * - Client-side: `AuthProvider` does the same on mount, exposes via\n * React context.\n *\n * **Bare vs namespaced keys.** Internally we store namespaced keys\n * (`<module_slug>:<key>`) so the JWT shape supports multi-install in\n * the future. Authors write BARE keys (`tasks:delete`, `editor`) from\n * inside their own module — the helpers transparently match either.\n *\n * The bare-key match is `endsWith(':' + bareKey)` — safe because role\n * keys can't contain colons (enforced by the parser regex in P12.1)\n * and permission keys use colons as namespace separators within a\n * fixed shape. Cross-module references must use the full namespaced\n * form explicitly.\n */\n\nimport type { RbacMeResponse, Session } from './types.js';\n\n/**\n * Does the caller's resolved permission set contain `key`? Accepts\n * either the bare form (`tasks:delete`) or the fully-namespaced form\n * (`tasks-app:tasks:delete`).\n *\n * Pure function over a `RbacMeResponse`-shaped object — usable from\n * any context. Returns `false` if the set is missing/undefined (the\n * default-deny floor); never throws.\n */\nexport function permissionGranted(\n rbac: Pick<RbacMeResponse, 'permissions'> | null | undefined,\n key: string,\n): boolean {\n if (!rbac || !rbac.permissions) return false;\n return matchKey(rbac.permissions, key);\n}\n\n/**\n * Does the caller hold `roleKey` (bare or namespaced) in their role\n * set? Returns false if no RBAC data present.\n */\nexport function roleGranted(\n rbac: Pick<RbacMeResponse, 'roles'> | null | undefined,\n roleKey: string,\n): boolean {\n if (!rbac || !rbac.roles) return false;\n return matchKey(rbac.roles, roleKey);\n}\n\n/**\n * Does the resolved set contain ANY of the requested permissions?\n * Used by `withAnyPermission()` middleware + the `any: [...]` rule\n * shape in `withAuth.permissionRules`.\n */\nexport function anyPermissionGranted(\n rbac: Pick<RbacMeResponse, 'permissions'> | null | undefined,\n keys: readonly string[],\n): boolean {\n return keys.some((k) => permissionGranted(rbac, k));\n}\n\n/**\n * Does the resolved set contain ALL of the requested permissions?\n * Used by `withAllPermissions()` middleware.\n */\nexport function allPermissionsGranted(\n rbac: Pick<RbacMeResponse, 'permissions'> | null | undefined,\n keys: readonly string[],\n): boolean {\n return keys.every((k) => permissionGranted(rbac, k));\n}\n\n/**\n * Extract just the RBAC slice from a `Session`. Tiny helper for\n * helpers that want to pass either a Session or a `RbacMeResponse`\n * shape uniformly.\n */\nexport function rbacOf(session: Session | null | undefined):\n | Pick<RbacMeResponse, 'roles' | 'permissions'>\n | null {\n if (!session) return null;\n return {\n roles: session.rbacRoles ?? [],\n permissions: session.rbacPermissions ?? [],\n };\n}\n\n// ── Private match helper ───────────────────────────────────────────\n\n/**\n * Bare-or-namespaced match against a stored key set.\n *\n * exact match → granted\n * key ends with `:bare` → granted (namespaced match)\n *\n * The `:` prefix on the suffix check prevents `'admin'` from\n * matching a stored `'super-admin'`. Role + permission keys never\n * start with `:` and never contain it un-namespaced, so this match\n * is safe across both kinds.\n */\nfunction matchKey(stored: readonly string[], queryKey: string): boolean {\n if (stored.length === 0) return false;\n for (const s of stored) {\n if (s === queryKey) return true;\n if (s.endsWith(':' + queryKey)) return true;\n }\n return false;\n}\n","/**\n * Server-side auth helpers — used from React Server Components, route\n * handlers, and server actions. Imports `next/headers` lazily so the\n * subpath remains importable from non-Next environments (tests, unit\n * fixtures) without crashing on missing peer deps.\n *\n * Consumers:\n * import { getServerSession, exchangeCode } from '@dashai/sdk/auth/server';\n *\n * Public surface:\n * - `getServerSession(opts?)` — read the current session, or null\n * - `exchangeCode(code, opts?)` — exchange an SSO one-time code for a session\n * - `signOut(opts?)` — clear the session cookie + tell the backend\n *\n * All three accept an optional `AuthOptions` argument. Defaults come\n * from `DASHWISE_*` env vars; see `config.ts`.\n */\n\nimport { DashwiseError } from '../data/errors.js';\nimport { resolveAuthOptions } from './config.js';\nimport {\n AuthErrorCode,\n type AuthOptions,\n type ExchangeResult,\n type RbacMeResponse,\n type Session,\n} from './types.js';\nimport {\n allPermissionsGranted,\n anyPermissionGranted,\n permissionGranted,\n rbacOf,\n roleGranted,\n} from './rbac.js';\n\n// ── Lazy-loaded next/headers shim ──────────────────────────────────────\n\n/**\n * Read the session cookie from Next.js's `cookies()` helper.\n *\n * `next/headers` is a peer dep — we import it dynamically so:\n * (a) the SDK builds without `next` installed\n * (b) consumers who only use the data plane don't pay for next's footprint\n * (c) tests can mock the cookie store by passing `cookieValue` explicitly\n *\n * Returns the cookie value or `null` if absent / not in a Next context.\n */\nasync function readSessionCookie(cookieName: string): Promise<string | null> {\n try {\n // The dynamic import path is hoisted by bundlers, but the call\n // itself only fires at runtime — if `next` isn't installed, we\n // return null instead of crashing.\n const mod = await import('next/headers').catch(() => null);\n if (!mod) return null;\n const cookieStore = await mod.cookies();\n const cookie = cookieStore.get(cookieName);\n return cookie?.value ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Set the session cookie via Next.js's `cookies()` helper (route\n * handlers + server actions can mutate cookies; RSC reads are\n * read-only).\n *\n * No-op if `next/headers` isn't importable.\n */\nasync function writeSessionCookie(\n cookieName: string,\n value: string,\n maxAgeSeconds: number,\n): Promise<void> {\n try {\n const mod = await import('next/headers').catch(() => null);\n if (!mod) return;\n const cookieStore = await mod.cookies();\n cookieStore.set(cookieName, value, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n path: '/',\n maxAge: maxAgeSeconds,\n });\n } catch {\n // Mutating cookies outside a route handler / server action throws\n // — swallow + log nothing. Callers should be invoking this from\n // a context where cookies are writable.\n }\n}\n\nasync function clearSessionCookie(cookieName: string): Promise<void> {\n try {\n const mod = await import('next/headers').catch(() => null);\n if (!mod) return;\n const cookieStore = await mod.cookies();\n cookieStore.set(cookieName, '', {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n path: '/',\n maxAge: 0,\n });\n } catch {\n // Same caveat as writeSessionCookie.\n }\n}\n\n// ── Backend envelope mapping ──────────────────────────────────────────\n\ninterface RawSessionEnvelope {\n user?: { id?: number; email?: string; name?: string | null };\n workspace_id?: number;\n workspaceId?: number;\n role?: string;\n installation_id?: number;\n installationId?: number;\n module_id?: number;\n moduleId?: number;\n module_slug?: string;\n moduleSlug?: string;\n expires_at?: number;\n expiresAt?: number;\n}\n\n/**\n * Normalize backend snake_case → SDK camelCase. The backend's\n * `/api/auth/sessions/me` may emit either depending on the controller\n * shape; accept both so we're not chasing serialization conventions.\n */\nfunction parseSession(raw: unknown): Session | null {\n if (!raw || typeof raw !== 'object') return null;\n const r = raw as RawSessionEnvelope;\n if (!r.user || typeof r.user.id !== 'number' || typeof r.user.email !== 'string') {\n return null;\n }\n const role = r.role;\n if (role !== 'admin' && role !== 'editor' && role !== 'viewer') {\n return null;\n }\n const workspaceId = r.workspaceId ?? r.workspace_id;\n if (typeof workspaceId !== 'number') return null;\n const expiresAt = r.expiresAt ?? r.expires_at;\n if (typeof expiresAt !== 'number') return null;\n\n const installationId = r.installationId ?? r.installation_id;\n const moduleId = r.moduleId ?? r.module_id;\n const moduleSlug = r.moduleSlug ?? r.module_slug;\n\n return {\n user: {\n id: r.user.id,\n email: r.user.email,\n name: r.user.name ?? null,\n },\n workspaceId,\n role,\n ...(typeof installationId === 'number' ? { installationId } : {}),\n ...(typeof moduleId === 'number' ? { moduleId } : {}),\n ...(typeof moduleSlug === 'string' ? { moduleSlug } : {}),\n expiresAt,\n };\n}\n\n// ── Public API ────────────────────────────────────────────────────────\n\n/**\n * Get the current session, or `null` if the user isn't signed in.\n *\n * Reads the session cookie from `next/headers` and validates it\n * against the DashWise backend at `/api/auth/sessions/me`. Returns\n * the validated `Session` on success.\n *\n * Cache: this call is uncached on purpose. The backend's `/me`\n * endpoint is cheap (single DB row by indexed PK). Consumers that\n * call `getServerSession()` multiple times per request should\n * memoize at the React Server Component level.\n *\n * @example\n * import { getServerSession } from '@dashai/sdk/auth/server';\n * import { redirect } from 'next/navigation';\n *\n * export default async function DashboardPage() {\n * const session = await getServerSession();\n * if (!session) redirect('/api/auth/sign-in');\n * return <h1>Hi {session.user.email}</h1>;\n * }\n */\nexport async function getServerSession(options: AuthOptions = {}): Promise<Session | null> {\n const cfg = resolveAuthOptions(options);\n const cookieValue = await readSessionCookie(cfg.cookieName);\n if (!cookieValue) return null;\n\n const cookieHeader = `${cfg.cookieName}=${encodeURIComponent(cookieValue)}`;\n const sessionUrl = `${cfg.apiBaseUrl}/api/auth/sessions/me`;\n\n let sessionRes: Response;\n try {\n sessionRes = await cfg.fetch(sessionUrl, {\n method: 'GET',\n headers: {\n Cookie: cookieHeader,\n Accept: 'application/json',\n },\n });\n } catch {\n return null;\n }\n\n if (!sessionRes.ok) {\n // 401 / 403 from /me means the cookie is no longer valid. Treat\n // identically to \"no cookie\" — the consumer's app code redirects\n // to sign-in.\n return null;\n }\n\n const sessionBody = (await sessionRes.json().catch(() => null)) as unknown;\n const session = parseSession(sessionBody);\n if (!session) return null;\n\n // P12.4: when we have an installation context, fetch the RBAC\n // resolution side-channel in parallel + merge into the session.\n // We don't block session resolution on it — RBAC fetch failures\n // degrade gracefully to \"no permissions\" (default-deny floor).\n if (session.installationId !== undefined) {\n const rbac = await fetchRbacMe(\n cfg.apiBaseUrl,\n cookieHeader,\n session.installationId,\n cfg.fetch,\n );\n if (rbac) {\n session.rbacRoles = rbac.roles;\n session.rbacPermissions = rbac.permissions;\n }\n }\n\n return session;\n}\n\n/**\n * Fetch `/api/installations/:id/rbac/me` for the active session.\n * Returns the resolved roles + permissions, or null on any failure\n * (network, HTTP error, schema mismatch). Failure is non-fatal —\n * the caller treats null as \"no permissions\" (default-deny).\n *\n * Exported so `auth/middleware.ts` can reuse the same code path\n * without re-implementing the request shape.\n */\nexport async function fetchRbacMe(\n apiBaseUrl: string,\n cookieHeader: string,\n installationId: number,\n fetchImpl: typeof globalThis.fetch,\n): Promise<RbacMeResponse | null> {\n const url = `${apiBaseUrl}/api/installations/${installationId}/rbac/me`;\n let res: Response;\n try {\n res = await fetchImpl(url, {\n method: 'GET',\n headers: {\n Cookie: cookieHeader,\n Accept: 'application/json',\n },\n });\n } catch {\n return null;\n }\n if (!res.ok) return null;\n const body = (await res.json().catch(() => null)) as unknown;\n if (!body || typeof body !== 'object') return null;\n const rolesRaw = (body as Record<string, unknown>).roles;\n const permsRaw = (body as Record<string, unknown>).permissions;\n if (!Array.isArray(rolesRaw) || !Array.isArray(permsRaw)) return null;\n return {\n roles: rolesRaw.filter((r): r is string => typeof r === 'string'),\n permissions: permsRaw.filter((p): p is string => typeof p === 'string'),\n };\n}\n\n/**\n * Exchange an SSO one-time `code` (received at the OAuth callback\n * URL `?code=...`) for a session. On success, sets the session\n * cookie via `next/headers` AND returns the decoded session so the\n * caller can chain a `redirect(returnTo)`.\n *\n * Call from your `/api/auth/callback/route.ts`:\n *\n * @example\n * import { exchangeCode } from '@dashai/sdk/auth/server';\n * import { NextResponse } from 'next/server';\n *\n * export async function GET(request: Request) {\n * const url = new URL(request.url);\n * const code = url.searchParams.get('code');\n * const returnTo = url.searchParams.get('return_to') ?? '/';\n * if (!code) return NextResponse.redirect(new URL('/', request.url));\n * await exchangeCode(code); // sets the cookie\n * return NextResponse.redirect(new URL(returnTo, request.url));\n * }\n *\n * Throws `DashwiseError` with `code === 'INVALID_EXCHANGE_CODE'` if\n * the backend rejects (expired / replay / forged code).\n */\nexport async function exchangeCode(\n code: string,\n options: AuthOptions = {},\n): Promise<ExchangeResult> {\n const cfg = resolveAuthOptions(options);\n const url = `${cfg.apiBaseUrl}/api/auth/sessions/exchange`;\n\n let res: Response;\n try {\n res = await cfg.fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({ code }),\n });\n } catch (err) {\n throw new DashwiseError(AuthErrorCode.PROTOCOL_ERROR, 'Auth exchange request failed', {\n cause: err,\n });\n }\n\n if (!res.ok) {\n throw new DashwiseError(\n AuthErrorCode.INVALID_EXCHANGE_CODE,\n `Auth exchange rejected (HTTP ${res.status})`,\n { status: res.status },\n );\n }\n\n const body = (await res.json().catch(() => null)) as\n | {\n session_token?: string;\n sessionToken?: string;\n max_age_seconds?: number;\n maxAgeSeconds?: number;\n session?: unknown;\n }\n | null;\n if (!body) {\n throw new DashwiseError(\n AuthErrorCode.PROTOCOL_ERROR,\n 'Auth exchange returned an unparseable body',\n );\n }\n const sessionToken = body.sessionToken ?? body.session_token;\n const maxAgeSeconds = body.maxAgeSeconds ?? body.max_age_seconds;\n const session = parseSession(body.session);\n if (!sessionToken || typeof maxAgeSeconds !== 'number' || !session) {\n throw new DashwiseError(\n AuthErrorCode.PROTOCOL_ERROR,\n 'Auth exchange returned an invalid envelope',\n );\n }\n\n await writeSessionCookie(cfg.cookieName, sessionToken, maxAgeSeconds);\n\n return { sessionToken, maxAgeSeconds, session };\n}\n\n/**\n * Sign out the current user: clears the session cookie and notifies\n * the backend so the server-side session record can be revoked\n * before its natural expiry.\n *\n * Safe to call when not signed in (no-op). Returns nothing.\n *\n * Backend-side revocation is best-effort: if `/sign-out` fails, the\n * cookie is still cleared client-side, so the user's local session\n * is over regardless. The backend will reap the orphaned session\n * record on its next periodic sweep.\n */\nexport async function signOut(options: AuthOptions = {}): Promise<void> {\n const cfg = resolveAuthOptions(options);\n const cookieValue = await readSessionCookie(cfg.cookieName);\n await clearSessionCookie(cfg.cookieName);\n if (!cookieValue) return;\n\n const url = `${cfg.apiBaseUrl}/api/auth/sessions/sign-out`;\n try {\n await cfg.fetch(url, {\n method: 'POST',\n headers: {\n Cookie: `${cfg.cookieName}=${encodeURIComponent(cookieValue)}`,\n Accept: 'application/json',\n },\n });\n } catch {\n // Best-effort. Cookie is already cleared above.\n }\n}\n\n// ── Module RBAC server helpers (P12.4) ────────────────────────────────\n\n/**\n * Sync check: does the given session hold `permissionKey`?\n *\n * Accepts either the bare form (`tasks:delete`) or the namespaced\n * form (`tasks-app:tasks:delete`). Returns false if the session is\n * null OR has no RBAC data (default-deny floor).\n *\n * For consumers using `getServerSession()`, prefer the async variants\n * below — they handle the case where you forgot to call\n * `getServerSession()` first.\n *\n * @example\n * const session = await getServerSession();\n * if (!hasPermissionInSession(session, 'tasks:delete')) {\n * return new Response('Forbidden', { status: 403 });\n * }\n */\nexport function hasPermissionInSession(\n session: Session | null | undefined,\n permissionKey: string,\n): boolean {\n return permissionGranted(rbacOf(session), permissionKey);\n}\n\n/**\n * Sync check: does the given session hold `roleKey`?\n * Same semantics as `hasPermissionInSession`.\n */\nexport function hasRoleInSession(\n session: Session | null | undefined,\n roleKey: string,\n): boolean {\n return roleGranted(rbacOf(session), roleKey);\n}\n\n/**\n * Async convenience: fetch the session AND check a permission in\n * one call. Returns true iff a session exists + holds the key.\n *\n * Most server-component code paths look like:\n *\n * @example\n * if (!(await hasPermission('tasks:delete'))) {\n * return <Forbidden />;\n * }\n */\nexport async function hasPermission(\n permissionKey: string,\n options: AuthOptions = {},\n): Promise<boolean> {\n const session = await getServerSession(options);\n return hasPermissionInSession(session, permissionKey);\n}\n\n/**\n * Async convenience: as `hasPermission` but for roles.\n */\nexport async function hasRole(\n roleKey: string,\n options: AuthOptions = {},\n): Promise<boolean> {\n const session = await getServerSession(options);\n return hasRoleInSession(session, roleKey);\n}\n\n/**\n * Throw `DashwiseError('PERMISSION_DENIED')` if the session lacks\n * `permissionKey`. Pattern for guarding server actions + RSC\n * branches that should redirect-to-403 on failure.\n *\n * Throws `RBAC_UNAVAILABLE` if there's no session at all — distinct\n * from PERMISSION_DENIED so callers can branch on \"needs sign-in\"\n * vs \"signed in but forbidden\".\n *\n * Returns the loaded session on success — saves a second\n * `getServerSession()` call in handlers that need both.\n *\n * @example\n * import { requirePermission } from '@dashai/sdk/auth/server';\n *\n * export default async function DeletePanel() {\n * const session = await requirePermission('tasks:delete');\n * return <DeleteForm userEmail={session.user.email} />;\n * }\n */\nexport async function requirePermission(\n permissionKey: string,\n options: AuthOptions = {},\n): Promise<Session> {\n const session = await getServerSession(options);\n if (!session) {\n throw new DashwiseError(\n AuthErrorCode.RBAC_UNAVAILABLE,\n `requirePermission('${permissionKey}'): no active session`,\n { status: 401, context: { permission: permissionKey } },\n );\n }\n if (!hasPermissionInSession(session, permissionKey)) {\n throw new DashwiseError(\n AuthErrorCode.PERMISSION_DENIED,\n `requirePermission('${permissionKey}'): denied`,\n {\n status: 403,\n context: {\n permission: permissionKey,\n holds: session.rbacPermissions ?? [],\n },\n },\n );\n }\n return session;\n}\n\n/**\n * Throw `PERMISSION_DENIED` unless the session holds at least one of\n * the requested permissions. Useful for endpoints with multiple\n * acceptable scopes.\n */\nexport async function requireAnyPermission(\n permissionKeys: readonly string[],\n options: AuthOptions = {},\n): Promise<Session> {\n const session = await getServerSession(options);\n if (!session) {\n throw new DashwiseError(\n AuthErrorCode.RBAC_UNAVAILABLE,\n `requireAnyPermission([${permissionKeys.join(', ')}]): no active session`,\n { status: 401, context: { permissions: [...permissionKeys] } },\n );\n }\n if (!anyPermissionGranted(rbacOf(session), permissionKeys)) {\n throw new DashwiseError(\n AuthErrorCode.PERMISSION_DENIED,\n `requireAnyPermission([${permissionKeys.join(', ')}]): none granted`,\n {\n status: 403,\n context: {\n permissions: [...permissionKeys],\n holds: session.rbacPermissions ?? [],\n },\n },\n );\n }\n return session;\n}\n\n/**\n * Throw `PERMISSION_DENIED` unless the session holds all of the\n * requested permissions. Useful for multi-permission gating where\n * partial grants aren't acceptable.\n */\nexport async function requireAllPermissions(\n permissionKeys: readonly string[],\n options: AuthOptions = {},\n): Promise<Session> {\n const session = await getServerSession(options);\n if (!session) {\n throw new DashwiseError(\n AuthErrorCode.RBAC_UNAVAILABLE,\n `requireAllPermissions([${permissionKeys.join(', ')}]): no active session`,\n { status: 401, context: { permissions: [...permissionKeys] } },\n );\n }\n if (!allPermissionsGranted(rbacOf(session), permissionKeys)) {\n throw new DashwiseError(\n AuthErrorCode.PERMISSION_DENIED,\n `requireAllPermissions([${permissionKeys.join(', ')}]): missing one or more`,\n {\n status: 403,\n context: {\n permissions: [...permissionKeys],\n holds: session.rbacPermissions ?? [],\n },\n },\n );\n }\n return session;\n}\n\n/**\n * Throw `PERMISSION_DENIED` unless the session holds `roleKey`.\n * Sugar over `requirePermission` for role-centric handlers.\n */\nexport async function requireRole(\n roleKey: string,\n options: AuthOptions = {},\n): Promise<Session> {\n const session = await getServerSession(options);\n if (!session) {\n throw new DashwiseError(\n AuthErrorCode.RBAC_UNAVAILABLE,\n `requireRole('${roleKey}'): no active session`,\n { status: 401, context: { role: roleKey } },\n );\n }\n if (!hasRoleInSession(session, roleKey)) {\n throw new DashwiseError(\n AuthErrorCode.PERMISSION_DENIED,\n `requireRole('${roleKey}'): denied`,\n {\n status: 403,\n context: { role: roleKey, holds: session.rbacRoles ?? [] },\n },\n );\n }\n return session;\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/auth/types.ts
|
|
4
|
+
var AuthErrorCode = {
|
|
5
|
+
/** Cookie missing or invalid — caller should redirect to sign-in. */
|
|
6
|
+
NO_SESSION: "NO_SESSION",
|
|
7
|
+
/** Backend rejected the exchange code (expired / replay / forged). */
|
|
8
|
+
INVALID_EXCHANGE_CODE: "INVALID_EXCHANGE_CODE",
|
|
9
|
+
/** Backend rejected the session refresh (expired beyond refresh window). */
|
|
10
|
+
REFRESH_FAILED: "REFRESH_FAILED",
|
|
11
|
+
/** Backend returned an unexpected response. */
|
|
12
|
+
PROTOCOL_ERROR: "PROTOCOL_ERROR",
|
|
13
|
+
/**
|
|
14
|
+
* `requirePermission(...)` / `requireRole(...)` rejected because
|
|
15
|
+
* the current session lacks the requested permission/role (P12.4).
|
|
16
|
+
* Includes the requested key in the error's `context`.
|
|
17
|
+
*/
|
|
18
|
+
PERMISSION_DENIED: "PERMISSION_DENIED",
|
|
19
|
+
/**
|
|
20
|
+
* `requirePermission(...)` / `requireRole(...)` was called from a
|
|
21
|
+
* context without RBAC info — usually because the session has no
|
|
22
|
+
* `installationId` (the user isn't inside an installed module),
|
|
23
|
+
* or the `/rbac/me` fetch failed silently. Callers in this state
|
|
24
|
+
* should fall back to anon UI or surface a missing-context error.
|
|
25
|
+
*/
|
|
26
|
+
RBAC_UNAVAILABLE: "RBAC_UNAVAILABLE"
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
exports.AuthErrorCode = AuthErrorCode;
|
|
30
|
+
//# sourceMappingURL=types.cjs.map
|
|
31
|
+
//# sourceMappingURL=types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/types.ts"],"names":[],"mappings":";;;AAkJO,IAAM,aAAA,GAAgB;AAAA;AAAA,EAE3B,UAAA,EAAY,YAAA;AAAA;AAAA,EAEZ,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAEvB,cAAA,EAAgB,gBAAA;AAAA;AAAA,EAEhB,cAAA,EAAgB,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,iBAAA,EAAmB,mBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQnB,gBAAA,EAAkB;AACpB","file":"types.cjs","sourcesContent":["/**\n * Public types for the @dashai/sdk/auth/* subpaths.\n *\n * The DashWise NestJS backend is the identity provider (IDP); these\n * types describe the SSO + session contract the SDK consumes. Changes\n * here are SemVer-significant — every Next.js module + custom-runtime\n * deployment depends on this shape.\n */\n\n/**\n * Workspace-scoped session for a logged-in user. Returned by\n * `getServerSession()` (server-side) and `useSession()` (client-side).\n *\n * `user` carries identity; `workspaceId` + `role` carry workspace\n * scoping; `installationId` + `moduleId` + `moduleSlug` carry\n * module-install context (present in custom-module runtimes and\n * post-install AI-builder previews; absent in pre-install /\n * marketplace / hand-author dev contexts).\n *\n * `expiresAt` is wall-clock ms (Unix epoch). The session is auto-\n * refreshed by the SDK middleware/server helpers while the user is\n * active; consumers shouldn't manually compare against `Date.now()`\n * unless they're displaying a countdown to the user.\n */\nexport interface Session {\n user: {\n id: number;\n email: string;\n /** Display name. Null if the user hasn't set one yet. */\n name: string | null;\n };\n workspaceId: number;\n role: 'admin' | 'editor' | 'viewer';\n installationId?: number;\n moduleId?: number;\n moduleSlug?: string;\n /** Wall-clock expiry, Unix ms. */\n expiresAt: number;\n /**\n * Module RBAC roles for the current installation (P12.4). Populated\n * by the SDK via a parallel `/api/installations/:id/rbac/me` fetch\n * when `installationId` is set. Values are NAMESPACED keys —\n * `<module_slug>:<role>` — to leave room for future cross-module\n * grants without breaking the shape.\n *\n * Empty array means the user has no role grants for this install\n * (denied to anything role-gated). `undefined` means the SDK\n * hasn't fetched the RBAC data yet (sessions outside an install\n * context, or transient pre-resolution state).\n */\n rbacRoles?: string[];\n\n /**\n * Module RBAC permissions for the current installation (P12.4).\n * Same shape + nullability semantics as `rbacRoles`. Values are\n * namespaced (`<module_slug>:<permission_key>`); the SDK's\n * `hasPermission` / `requirePermission` helpers accept either the\n * bare or the namespaced form.\n *\n * This is the resolved permission set — already expanded via\n * `includes` graph traversal on the backend — so client-side\n * checks are O(1) set-membership.\n */\n rbacPermissions?: string[];\n}\n\n/**\n * Response shape of `GET /api/installations/:id/rbac/me`. The SDK\n * fetches this in parallel with `/api/auth/sessions/me` when the\n * session has an `installationId`.\n *\n * Both arrays are NAMESPACED (`<module_slug>:<key>`) — the SDK's\n * permission/role helpers strip the namespace at lookup time so\n * authors write bare keys (`tasks:delete`, `editor`).\n */\nexport interface RbacMeResponse {\n roles: string[];\n permissions: string[];\n}\n\n/**\n * Status returned by `useSession()` on the client. `loading` is the\n * initial render before the session fetch resolves; SSR-friendly\n * apps may want to gate suspense or skeletons on this.\n */\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\n/**\n * Shared configuration accepted by every auth helper. All fields are\n * optional; defaults come from the runtime env (`DASHWISE_*`) or\n * sensible static fallbacks.\n *\n * Pass an explicit object to override per-call (useful for tests +\n * for runtimes that can't read env vars at request time).\n */\nexport interface AuthOptions {\n /**\n * Base URL for the DashWise backend API (e.g.\n * `https://api.dashwise.io`). Used for `/api/auth/sessions/me`,\n * `/api/auth/sessions/exchange`, etc. Defaults to\n * `process.env.DASHWISE_API_URL`.\n */\n apiBaseUrl?: string;\n\n /**\n * Base URL for the DashWise main app's SSO entry point (e.g.\n * `https://app.dashwise.io`). Used for the initial redirect from\n * module middleware. Defaults to `process.env.DASHWISE_AUTH_URL`,\n * falling back to `apiBaseUrl` with no path suffix.\n */\n authBaseUrl?: string;\n\n /**\n * Name of the session cookie. Defaults to\n * `process.env.DASHWISE_SESSION_COOKIE_NAME` or `'dashwise.session'`.\n * Cookie scope is configured by the backend on set; the SDK only\n * reads/clears it.\n */\n cookieName?: string;\n\n /**\n * Optional fetch override (testing / custom HTTP agent). Defaults\n * to `globalThis.fetch`.\n */\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Response shape from `POST /api/auth/sessions/exchange`. The\n * `session_token` is the opaque cookie value to set; the consumer\n * shouldn't decode or store it elsewhere.\n */\nexport interface ExchangeResult {\n /** Opaque session cookie value (JWT under the hood). */\n sessionToken: string;\n /** Cookie max-age in seconds (matches the JWT exp). */\n maxAgeSeconds: number;\n /** Already-decoded session — saves an immediate /me round-trip. */\n session: Session;\n}\n\n/**\n * Errors thrown by the auth layer. Mirrors the data-plane error model\n * (subclass of `DashwiseError`) so consumers can catch all SDK errors\n * uniformly.\n */\nexport const AuthErrorCode = {\n /** Cookie missing or invalid — caller should redirect to sign-in. */\n NO_SESSION: 'NO_SESSION',\n /** Backend rejected the exchange code (expired / replay / forged). */\n INVALID_EXCHANGE_CODE: 'INVALID_EXCHANGE_CODE',\n /** Backend rejected the session refresh (expired beyond refresh window). */\n REFRESH_FAILED: 'REFRESH_FAILED',\n /** Backend returned an unexpected response. */\n PROTOCOL_ERROR: 'PROTOCOL_ERROR',\n /**\n * `requirePermission(...)` / `requireRole(...)` rejected because\n * the current session lacks the requested permission/role (P12.4).\n * Includes the requested key in the error's `context`.\n */\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n /**\n * `requirePermission(...)` / `requireRole(...)` was called from a\n * context without RBAC info — usually because the session has no\n * `installationId` (the user isn't inside an installed module),\n * or the `/rbac/me` fetch failed silently. Callers in this state\n * should fall back to anon UI or surface a missing-context error.\n */\n RBAC_UNAVAILABLE: 'RBAC_UNAVAILABLE',\n} as const;\n\nexport type AuthErrorCode = (typeof AuthErrorCode)[keyof typeof AuthErrorCode];\n"]}
|