@zjazj/server 0.0.0-stage → 0.0.1

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 CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @zjazj/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Backend runtime for platform apps on Hono: token verification, permissions, typed errors, logging and tenant-safe database access.
4
+
5
+ ```ts
6
+ import { createApp, requirePermission } from '@zjazj/server'
7
+ import { db } from '@zjazj/server/db'
8
+
9
+ const app = createApp({ manifest, permissions, database: true })
10
+
11
+ const routes = app.api.get('/items', requirePermission('inventory:item:read'), async (c) =>
12
+ c.json(await db(c).select().from(items)),
13
+ )
14
+
15
+ export type AppType = typeof routes
16
+ export default app
17
+ ```
18
+
19
+ | Import | Contents |
20
+ | --- | --- |
21
+ | `@zjazj/server` | `createApp`, auth, errors, pagination, request ids, URL guard |
22
+ | `@zjazj/server/db` | `tenantTable`, `db(c)`, `withTenant`, migrations |
23
+ | `@zjazj/server/log` | `log`, `audit` |
24
+ | `@zjazj/server/dev` | the local dev identity |
25
+ | `@zjazj/server/testing` | a token issuer for tests |
26
+
27
+ `db(c)` can only see rows of the caller's tenant. The database enforces it with row-level security.
28
+
29
+ Part of [platform-cli](https://github.com/zjazj/platform-cli). All `@zjazj/*` packages share one version. Install them at the same version.
@@ -0,0 +1,65 @@
1
+ import { MiddlewareHandler, Context } from 'hono';
2
+ import { jwtVerify, JWTPayload } from 'jose';
3
+
4
+ /** The authenticated caller. */
5
+ interface AuthUser {
6
+ /** The identity provider's user id. An opaque string. */
7
+ id: string;
8
+ /** The tenant the token was issued for. A UUID. */
9
+ tenantId: string;
10
+ tenantSlug: string;
11
+ username: string;
12
+ roles: string[];
13
+ permissions: string[];
14
+ /** IANA time zone of the tenant, when the token carries one. */
15
+ timeZone?: string;
16
+ /** True only for the local dev identity. */
17
+ isDev?: boolean;
18
+ }
19
+ /** Organization tokens carry this audience prefix followed by the organization id. */
20
+ declare const ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
21
+ type VerifyKey = Parameters<typeof jwtVerify>[1];
22
+ interface VerifierOptions {
23
+ /** The token issuer, for example `https://auth.example.com/oidc`. */
24
+ issuer: string;
25
+ /** A fixed audience. Leave unset to accept organization tokens. */
26
+ audience?: string;
27
+ /** Defaults to `<issuer>/jwks`. */
28
+ jwksUri?: string;
29
+ /** A key or key resolver, used instead of fetching the JWKS. Meant for tests. */
30
+ key?: VerifyKey;
31
+ algorithms?: string[];
32
+ }
33
+ interface Verifier {
34
+ verify(token: string): Promise<AuthUser>;
35
+ }
36
+ /** Project verified token claims into an `AuthUser`. */
37
+ declare function userFromClaims(claims: JWTPayload): AuthUser;
38
+ /** Build a verifier for tokens issued by the platform's identity provider. */
39
+ declare function createVerifier(options: VerifierOptions): Verifier;
40
+ type Env = Record<string, string | undefined>;
41
+ /** Build the verifier from `LOGTO_ISSUER`, `LOGTO_AUDIENCE` and `LOGTO_JWKS_URI`. */
42
+ declare function verifierFromEnv(env?: Env): Verifier | undefined;
43
+ declare function bearerToken(header: string | undefined): string | undefined;
44
+ interface AuthenticateOptions {
45
+ verifier?: Verifier;
46
+ env?: Env;
47
+ }
48
+ /**
49
+ * Require an authenticated caller. On success the user is available through `getUser(c)`.
50
+ * With the dev identity enabled no token is verified and every request is the dev user.
51
+ */
52
+ declare function authenticate(options?: AuthenticateOptions): MiddlewareHandler;
53
+ /** The authenticated user of this request. Throws 401 when the route is not authenticated. */
54
+ declare function getUser(c: Context): AuthUser;
55
+ /** Require every listed permission. Wildcards in the granted set count. */
56
+ declare function requirePermission(...codes: string[]): MiddlewareHandler;
57
+ /** Require at least one of the listed roles. */
58
+ declare function requireRole(...roles: string[]): MiddlewareHandler;
59
+ declare module 'hono' {
60
+ interface ContextVariableMap {
61
+ user: AuthUser;
62
+ }
63
+ }
64
+
65
+ export { type AuthUser as A, ORGANIZATION_AUDIENCE_PREFIX as O, type Verifier as V, type AuthenticateOptions as a, type VerifierOptions as b, authenticate as c, bearerToken as d, createVerifier as e, requireRole as f, getUser as g, requirePermission as r, userFromClaims as u, verifierFromEnv as v };
@@ -0,0 +1,87 @@
1
+ import {
2
+ getRequestContext
3
+ } from "./chunk-ERGI2X5S.js";
4
+
5
+ // src/log.ts
6
+ import pino from "pino";
7
+ var baseFields = {};
8
+ var logger = build();
9
+ function defaultLevel() {
10
+ if (process.env.LOG_LEVEL) return process.env.LOG_LEVEL;
11
+ return process.env.NODE_ENV === "test" || process.env.VITEST ? "silent" : "info";
12
+ }
13
+ function build() {
14
+ return pino({
15
+ level: defaultLevel(),
16
+ base: baseFields,
17
+ timestamp: pino.stdTimeFunctions.isoTime,
18
+ formatters: { level: (label) => ({ level: label }) },
19
+ // Every line written during a request carries who made it and for which tenant.
20
+ mixin() {
21
+ const context = getRequestContext();
22
+ if (!context) return {};
23
+ const fields = { request_id: context.requestId };
24
+ if (context.user) {
25
+ fields.tenant_id = context.user.tenantId;
26
+ fields.user_id = context.user.id;
27
+ }
28
+ return fields;
29
+ },
30
+ redact: {
31
+ paths: [
32
+ "authorization",
33
+ "token",
34
+ "password",
35
+ "secret",
36
+ "*.authorization",
37
+ "*.token",
38
+ "*.password",
39
+ "*.secret",
40
+ "headers.authorization",
41
+ "headers.cookie"
42
+ ],
43
+ censor: "[redacted]"
44
+ }
45
+ });
46
+ }
47
+ function configureLog(fields) {
48
+ baseFields = { ...fields };
49
+ logger = build();
50
+ }
51
+ function write(level) {
52
+ return (message, fields) => {
53
+ logger[level](fields ?? {}, message);
54
+ };
55
+ }
56
+ var log = {
57
+ debug: write("debug"),
58
+ info: write("info"),
59
+ warn: write("warn"),
60
+ error: write("error")
61
+ };
62
+ function audit(action, details = {}) {
63
+ logger.info({ type: "audit", action, ...details }, action);
64
+ }
65
+ function requestLogger() {
66
+ return async (c, next) => {
67
+ const started = performance.now();
68
+ await next();
69
+ const status = c.res.status;
70
+ const fields = {
71
+ type: "access",
72
+ method: c.req.method,
73
+ path: c.req.path,
74
+ status,
75
+ duration_ms: Math.round(performance.now() - started)
76
+ };
77
+ if (status >= 500) logger.error(fields, "request failed");
78
+ else logger.info(fields, "request");
79
+ };
80
+ }
81
+
82
+ export {
83
+ configureLog,
84
+ log,
85
+ audit,
86
+ requestLogger
87
+ };
@@ -0,0 +1,142 @@
1
+ import {
2
+ getRequestId
3
+ } from "./chunk-ERGI2X5S.js";
4
+
5
+ // src/errors.ts
6
+ import { HTTPException } from "hono/http-exception";
7
+ var AppError = class extends Error {
8
+ code;
9
+ status;
10
+ field;
11
+ constructor(message, options = {}) {
12
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
13
+ this.name = new.target.name;
14
+ this.code = options.code ?? "app_error";
15
+ this.status = options.status ?? 400;
16
+ this.field = options.field;
17
+ }
18
+ };
19
+ var UnauthorizedError = class extends AppError {
20
+ constructor(message = "Authentication required", options = {}) {
21
+ super(message, { code: "unauthorized", status: 401, ...options });
22
+ }
23
+ };
24
+ var ForbiddenError = class extends AppError {
25
+ constructor(message = "Forbidden", options = {}) {
26
+ super(message, { code: "forbidden", status: 403, ...options });
27
+ }
28
+ };
29
+ var NotFoundError = class extends AppError {
30
+ constructor(message = "Not found", options = {}) {
31
+ super(message, { code: "not_found", status: 404, ...options });
32
+ }
33
+ };
34
+ var ConflictError = class extends AppError {
35
+ constructor(message = "Conflict", options = {}) {
36
+ super(message, { code: "conflict", status: 409, ...options });
37
+ }
38
+ };
39
+ var ValidationError = class extends AppError {
40
+ constructor(message, field, options = {}) {
41
+ super(message, { code: "validation_error", status: 422, field, ...options });
42
+ }
43
+ };
44
+ function withTrace(body) {
45
+ const traceId = getRequestId();
46
+ return traceId ? { ...body, trace_id: traceId } : body;
47
+ }
48
+ function toErrorResponse(error) {
49
+ if (error instanceof AppError) {
50
+ const body = { code: error.code, message: error.message };
51
+ if (error.field) body.field = error.field;
52
+ return { status: error.status, body: withTrace(body) };
53
+ }
54
+ if (error instanceof HTTPException) {
55
+ const code = error.status === 404 ? "not_found" : error.status >= 500 ? "internal_error" : "http_error";
56
+ return {
57
+ status: error.status,
58
+ body: withTrace({ code, message: error.message || "Request failed" })
59
+ };
60
+ }
61
+ return {
62
+ status: 500,
63
+ body: withTrace({ code: "internal_error", message: "Internal server error" })
64
+ };
65
+ }
66
+ function respond(c, status, body) {
67
+ if (status === 401) c.header("WWW-Authenticate", "Bearer");
68
+ return c.json(body, status);
69
+ }
70
+ function errorHandler(onUnexpected) {
71
+ return (error, c) => {
72
+ const { status, body } = toErrorResponse(error);
73
+ if (status >= 500) onUnexpected?.(error, c);
74
+ return respond(c, status, body);
75
+ };
76
+ }
77
+ function notFoundHandler() {
78
+ return (c) => respond(c, 404, withTrace({ code: "not_found", message: "Not found" }));
79
+ }
80
+
81
+ // src/ids.ts
82
+ import { randomBytes, randomInt } from "crypto";
83
+ var APP_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
84
+ var APP_ID_PATTERN = /^app[a-z0-9]{6}$/;
85
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
86
+ var ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
87
+ function isUuid(value) {
88
+ return typeof value === "string" && UUID_PATTERN.test(value);
89
+ }
90
+ function isValidAppName(value) {
91
+ return typeof value === "string" && APP_NAME_PATTERN.test(value);
92
+ }
93
+ function isValidAppId(value) {
94
+ return typeof value === "string" && APP_ID_PATTERN.test(value);
95
+ }
96
+ function assertValidAppId(value) {
97
+ if (!isValidAppId(value)) {
98
+ throw new Error(
99
+ `Invalid app id ${JSON.stringify(value)}. Expected "app" followed by six characters from [a-z0-9].`
100
+ );
101
+ }
102
+ }
103
+ function generateAppId() {
104
+ let id = "app";
105
+ for (let i = 0; i < 6; i += 1) id += ID_ALPHABET[randomInt(ID_ALPHABET.length)];
106
+ return id;
107
+ }
108
+ function uuidv7(now = Date.now()) {
109
+ const bytes = randomBytes(16);
110
+ const time = BigInt(now);
111
+ bytes[0] = Number(time >> 40n & 0xffn);
112
+ bytes[1] = Number(time >> 32n & 0xffn);
113
+ bytes[2] = Number(time >> 24n & 0xffn);
114
+ bytes[3] = Number(time >> 16n & 0xffn);
115
+ bytes[4] = Number(time >> 8n & 0xffn);
116
+ bytes[5] = Number(time & 0xffn);
117
+ bytes[6] = (bytes[6] ?? 0) & 15 | 112;
118
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
119
+ const hex = bytes.toString("hex");
120
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
121
+ }
122
+
123
+ export {
124
+ AppError,
125
+ UnauthorizedError,
126
+ ForbiddenError,
127
+ NotFoundError,
128
+ ConflictError,
129
+ ValidationError,
130
+ toErrorResponse,
131
+ errorHandler,
132
+ notFoundHandler,
133
+ APP_NAME_PATTERN,
134
+ APP_ID_PATTERN,
135
+ UUID_PATTERN,
136
+ isUuid,
137
+ isValidAppName,
138
+ isValidAppId,
139
+ assertValidAppId,
140
+ generateAppId,
141
+ uuidv7
142
+ };
@@ -0,0 +1,37 @@
1
+ // src/request-context.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { randomUUID } from "crypto";
4
+ var REQUEST_ID_HEADER = "X-Request-Id";
5
+ var REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
6
+ var storage = new AsyncLocalStorage();
7
+ function coerceRequestId(value) {
8
+ return value && REQUEST_ID_PATTERN.test(value) ? value : void 0;
9
+ }
10
+ function mintRequestId() {
11
+ return randomUUID().replaceAll("-", "");
12
+ }
13
+ function runWithRequestContext(context, fn) {
14
+ return storage.run(context, fn);
15
+ }
16
+ function getRequestContext() {
17
+ return storage.getStore();
18
+ }
19
+ function getRequestId() {
20
+ return storage.getStore()?.requestId;
21
+ }
22
+ function requestContext() {
23
+ return async (c, next) => {
24
+ const requestId = coerceRequestId(c.req.header(REQUEST_ID_HEADER)) ?? mintRequestId();
25
+ c.set("requestId", requestId);
26
+ await runWithRequestContext({ requestId }, next);
27
+ c.header(REQUEST_ID_HEADER, requestId);
28
+ };
29
+ }
30
+
31
+ export {
32
+ REQUEST_ID_HEADER,
33
+ coerceRequestId,
34
+ getRequestContext,
35
+ getRequestId,
36
+ requestContext
37
+ };
@@ -0,0 +1,61 @@
1
+ // src/dev.ts
2
+ var DEFAULT_DEV_TENANT_ID = "0190a000-0000-7000-8000-000000000001";
3
+ var DEV_TOKEN_PREFIX = "dev.";
4
+ function isDevIdentityEnabled(env = process.env) {
5
+ return env.ENV === "dev" && env.NODE_ENV !== "production";
6
+ }
7
+ function list(value, fallback) {
8
+ if (value === void 0) return fallback;
9
+ return value.split(",").map((item) => item.trim()).filter(Boolean);
10
+ }
11
+ function devIdentity(env = process.env) {
12
+ return {
13
+ id: env.DEV_USER_ID || "dev-user",
14
+ tenantId: env.DEV_TENANT_ID || DEFAULT_DEV_TENANT_ID,
15
+ tenantSlug: env.DEV_TENANT_SLUG || "dev",
16
+ username: env.DEV_USERNAME || "Dev User",
17
+ roles: list(env.DEV_ROLES, ["tenant_admin"]),
18
+ permissions: list(env.DEV_PERMISSIONS, ["*"]),
19
+ timeZone: env.DEV_TIME_ZONE || void 0,
20
+ isDev: true
21
+ };
22
+ }
23
+ function encodeDevToken(user) {
24
+ return DEV_TOKEN_PREFIX + Buffer.from(JSON.stringify(user), "utf8").toString("base64url");
25
+ }
26
+ function decodeDevToken(token) {
27
+ if (!token?.startsWith(DEV_TOKEN_PREFIX)) return void 0;
28
+ try {
29
+ const parsed = JSON.parse(
30
+ Buffer.from(token.slice(DEV_TOKEN_PREFIX.length), "base64url").toString("utf8")
31
+ );
32
+ return parsed && typeof parsed === "object" ? parsed : void 0;
33
+ } catch {
34
+ return void 0;
35
+ }
36
+ }
37
+ function resolveDevUser(token, env = process.env) {
38
+ const base = devIdentity(env);
39
+ const override = decodeDevToken(token);
40
+ if (!override) return base;
41
+ return {
42
+ ...base,
43
+ ...typeof override.id === "string" ? { id: override.id } : {},
44
+ ...typeof override.tenantId === "string" ? { tenantId: override.tenantId } : {},
45
+ ...typeof override.tenantSlug === "string" ? { tenantSlug: override.tenantSlug } : {},
46
+ ...typeof override.username === "string" ? { username: override.username } : {},
47
+ ...Array.isArray(override.roles) ? { roles: override.roles.map(String) } : {},
48
+ ...Array.isArray(override.permissions) ? { permissions: override.permissions.map(String) } : {},
49
+ ...typeof override.timeZone === "string" ? { timeZone: override.timeZone } : {}
50
+ };
51
+ }
52
+
53
+ export {
54
+ DEFAULT_DEV_TENANT_ID,
55
+ DEV_TOKEN_PREFIX,
56
+ isDevIdentityEnabled,
57
+ devIdentity,
58
+ encodeDevToken,
59
+ decodeDevToken,
60
+ resolveDevUser
61
+ };
@@ -0,0 +1,181 @@
1
+ import {
2
+ AppError,
3
+ ForbiddenError,
4
+ UUID_PATTERN,
5
+ UnauthorizedError
6
+ } from "./chunk-6IYKARAJ.js";
7
+ import {
8
+ isDevIdentityEnabled,
9
+ resolveDevUser
10
+ } from "./chunk-NMKEVYGN.js";
11
+ import {
12
+ getRequestContext
13
+ } from "./chunk-ERGI2X5S.js";
14
+
15
+ // src/permissions.ts
16
+ function permissionMatches(granted, code) {
17
+ if (granted.has(code) || granted.has("*")) return true;
18
+ const parts = code.split(":");
19
+ for (let keep = parts.length - 1; keep > 0; keep -= 1) {
20
+ const candidate = [...parts.slice(0, keep), ...Array(parts.length - keep).fill("*")].join(":");
21
+ if (granted.has(candidate)) return true;
22
+ }
23
+ return false;
24
+ }
25
+ function hasPermissions(granted, required) {
26
+ const set = granted instanceof Set ? granted : new Set(granted);
27
+ return required.every((code) => permissionMatches(set, code));
28
+ }
29
+ function definePermissions(definitions) {
30
+ const seen = /* @__PURE__ */ new Set();
31
+ for (const definition of definitions) {
32
+ if (!/^[a-z][a-z0-9-]*(:[a-z][a-z0-9-]*)+$/.test(definition.code)) {
33
+ throw new Error(`Invalid permission code: ${definition.code}`);
34
+ }
35
+ if (seen.has(definition.code)) {
36
+ throw new Error(`Duplicate permission code: ${definition.code}`);
37
+ }
38
+ seen.add(definition.code);
39
+ }
40
+ return definitions;
41
+ }
42
+
43
+ // src/auth.ts
44
+ import { createRemoteJWKSet, errors as joseErrors, jwtVerify } from "jose";
45
+ var ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
46
+ var DEFAULT_ALGORITHMS = ["ES384", "ES256", "RS256"];
47
+ function strings(value) {
48
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
49
+ }
50
+ function firstString(...values) {
51
+ return values.find((value) => typeof value === "string" && value !== "");
52
+ }
53
+ function userFromClaims(claims) {
54
+ const tenantId = claims.tenant_id;
55
+ if (typeof claims.sub !== "string" || claims.sub === "") {
56
+ throw new UnauthorizedError("token has no subject");
57
+ }
58
+ if (typeof tenantId !== "string" || !UUID_PATTERN.test(tenantId)) {
59
+ throw new UnauthorizedError("token has no tenant");
60
+ }
61
+ const roles = strings(claims.organization_roles);
62
+ return {
63
+ id: claims.sub,
64
+ tenantId: tenantId.toLowerCase(),
65
+ tenantSlug: firstString(claims.tenant_slug, claims.organization_id) ?? "",
66
+ username: firstString(claims.username, claims.name, claims.email) ?? claims.sub,
67
+ roles: roles.length > 0 ? roles : strings(claims.roles),
68
+ permissions: strings(claims.permissions),
69
+ timeZone: firstString(claims.tenant_time_zone)
70
+ };
71
+ }
72
+ function hasOrganizationAudience(audience) {
73
+ const values = Array.isArray(audience) ? audience : [audience];
74
+ return values.some(
75
+ (value) => typeof value === "string" && value.startsWith(ORGANIZATION_AUDIENCE_PREFIX)
76
+ );
77
+ }
78
+ function createVerifier(options) {
79
+ const issuer = options.issuer.replace(/\/+$/, "");
80
+ const key = options.key ?? createRemoteJWKSet(new URL(options.jwksUri ?? `${issuer}/jwks`));
81
+ const algorithms = options.algorithms ?? DEFAULT_ALGORITHMS;
82
+ return {
83
+ async verify(token) {
84
+ let payload;
85
+ try {
86
+ const result = await jwtVerify(token, key, {
87
+ issuer,
88
+ algorithms,
89
+ ...options.audience ? { audience: options.audience } : {}
90
+ });
91
+ payload = result.payload;
92
+ } catch (error) {
93
+ if (error instanceof joseErrors.JWTExpired) throw new UnauthorizedError("token expired");
94
+ throw new UnauthorizedError("invalid token", { cause: error });
95
+ }
96
+ if (!options.audience && !hasOrganizationAudience(payload.aud)) {
97
+ throw new UnauthorizedError("token audience is not an organization");
98
+ }
99
+ return userFromClaims(payload);
100
+ }
101
+ };
102
+ }
103
+ function verifierFromEnv(env = process.env) {
104
+ if (!env.LOGTO_ISSUER) return void 0;
105
+ return createVerifier({
106
+ issuer: env.LOGTO_ISSUER,
107
+ audience: env.LOGTO_AUDIENCE || void 0,
108
+ jwksUri: env.LOGTO_JWKS_URI || void 0
109
+ });
110
+ }
111
+ function bearerToken(header) {
112
+ if (!header) return void 0;
113
+ const match = /^Bearer\s+(\S+)$/i.exec(header.trim());
114
+ return match?.[1];
115
+ }
116
+ function authenticate(options = {}) {
117
+ const env = options.env ?? process.env;
118
+ const dev = isDevIdentityEnabled(env);
119
+ let verifier = options.verifier;
120
+ return async (c, next) => {
121
+ const token = bearerToken(c.req.header("Authorization"));
122
+ let user;
123
+ if (dev) {
124
+ user = resolveDevUser(token, env);
125
+ } else {
126
+ if (!token) throw new UnauthorizedError("missing bearer token");
127
+ verifier ??= verifierFromEnv(env);
128
+ if (!verifier) {
129
+ throw new AppError("Authentication is not configured: set LOGTO_ISSUER", {
130
+ code: "auth_not_configured",
131
+ status: 500
132
+ });
133
+ }
134
+ user = await verifier.verify(token);
135
+ }
136
+ c.set("user", user);
137
+ const context = getRequestContext();
138
+ if (context) context.user = user;
139
+ await next();
140
+ };
141
+ }
142
+ function getUser(c) {
143
+ const user = c.get("user");
144
+ if (!user) throw new UnauthorizedError();
145
+ return user;
146
+ }
147
+ function requirePermission(...codes) {
148
+ return async (c, next) => {
149
+ const user = getUser(c);
150
+ if (!hasPermissions(user.permissions, codes)) {
151
+ throw new ForbiddenError(`requires permission: ${[...codes].sort().join(", ")}`, {
152
+ code: "insufficient_permission"
153
+ });
154
+ }
155
+ await next();
156
+ };
157
+ }
158
+ function requireRole(...roles) {
159
+ return async (c, next) => {
160
+ const user = getUser(c);
161
+ if (!roles.some((role) => user.roles.includes(role))) {
162
+ throw new ForbiddenError(`requires one of: ${[...roles].sort().join(", ")}`);
163
+ }
164
+ await next();
165
+ };
166
+ }
167
+
168
+ export {
169
+ permissionMatches,
170
+ hasPermissions,
171
+ definePermissions,
172
+ ORGANIZATION_AUDIENCE_PREFIX,
173
+ userFromClaims,
174
+ createVerifier,
175
+ verifierFromEnv,
176
+ bearerToken,
177
+ authenticate,
178
+ getUser,
179
+ requirePermission,
180
+ requireRole
181
+ };