@zjazj/server 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import {
2
2
  createVerifier
3
- } from "./chunk-EIZ24ILA.js";
4
- import "./chunk-UWDDQH25.js";
5
- import "./chunk-NMKEVYGN.js";
3
+ } from "./chunk-7FPH47F6.js";
4
+ import {
5
+ createKeyVerifier,
6
+ isApiKey
7
+ } from "./chunk-OBKMOVBA.js";
8
+ import "./chunk-3X4RSAM6.js";
6
9
  import "./chunk-ERGI2X5S.js";
7
10
 
8
11
  // src/testing.ts
@@ -35,6 +38,31 @@ async function createTestIssuer(issuer = "https://auth.test/oidc") {
35
38
  }
36
39
  };
37
40
  }
41
+ function createTestKeyVerifier(keys) {
42
+ for (const key of Object.keys(keys)) {
43
+ if (!isApiKey(key)) throw new Error(`createTestKeyVerifier: ${key} does not start with pk_`);
44
+ }
45
+ return createKeyVerifier({
46
+ async check(key) {
47
+ const given = Object.hasOwn(keys, key) ? keys[key] : void 0;
48
+ if (!given) return void 0;
49
+ const kind = given.kind ?? "user";
50
+ const keyId = given.key_id ?? `key-${key.slice(3)}`;
51
+ return {
52
+ subject: kind === "tenant" ? `key:${keyId}` : "user-test",
53
+ key_id: keyId,
54
+ tenant_id: TEST_TENANT_ID,
55
+ tenant_slug: "org-test",
56
+ username: kind === "tenant" ? keyId : "user-test",
57
+ roles: [],
58
+ permissions: [],
59
+ ...given,
60
+ kind,
61
+ cache_seconds: 0
62
+ };
63
+ }
64
+ });
65
+ }
38
66
  var MCP_PROTOCOL_VERSION = "2026-07-28";
39
67
  function mcpRequest(url, method, params = {}, init = {}) {
40
68
  const named = params.name ?? params.uri;
@@ -46,6 +74,7 @@ function mcpRequest(url, method, params = {}, init = {}) {
46
74
  "MCP-Protocol-Version": MCP_PROTOCOL_VERSION,
47
75
  "Mcp-Method": method,
48
76
  ...typeof named === "string" ? { "Mcp-Name": named } : {},
77
+ ...init.token ? { Authorization: `Bearer ${init.token}` } : {},
49
78
  ...init.headers
50
79
  },
51
80
  body: JSON.stringify({
@@ -67,5 +96,6 @@ export {
67
96
  MCP_PROTOCOL_VERSION,
68
97
  TEST_TENANT_ID,
69
98
  createTestIssuer,
99
+ createTestKeyVerifier,
70
100
  mcpRequest
71
101
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zjazj/server",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "Backend runtime for platform apps: auth, logging, tenant-safe database access and app assembly on Hono.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -22,6 +22,10 @@
22
22
  "types": "./dist/db.d.ts",
23
23
  "default": "./dist/db.js"
24
24
  },
25
+ "./objects": {
26
+ "types": "./dist/objects.d.ts",
27
+ "default": "./dist/objects.js"
28
+ },
25
29
  "./dev": {
26
30
  "types": "./dist/dev.d.ts",
27
31
  "default": "./dist/dev.js"
@@ -1,81 +0,0 @@
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
- /**
17
- * Set when a platform operator works in this tenant as platform support. `until` is when
18
- * the session ends, in seconds since 1970. The subject is the operator.
19
- */
20
- support?: SupportSession;
21
- /** True only for the local dev identity. */
22
- isDev?: boolean;
23
- }
24
- /** A platform operator's time in a customer's tenant, as the token states it. */
25
- interface SupportSession {
26
- until: number;
27
- /** `support` today. */
28
- mode: string;
29
- }
30
- /**
31
- * The support session a token states, from `support_until` and `support_mode`. Both or
32
- * nothing: half of it is not a session. Mirrored in `@zjazj/web`.
33
- */
34
- declare function supportFromClaims(claims: Record<string, unknown>): SupportSession | undefined;
35
- /** Organization tokens carry this audience prefix followed by the organization id. */
36
- declare const ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
37
- type VerifyKey = Parameters<typeof jwtVerify>[1];
38
- interface VerifierOptions {
39
- /** The token issuer, for example `https://auth.example.com/oidc`. */
40
- issuer: string;
41
- /** A fixed audience. Leave unset to accept organization tokens. */
42
- audience?: string;
43
- /** Defaults to `<issuer>/jwks`. */
44
- jwksUri?: string;
45
- /** A key or key resolver, used instead of fetching the JWKS. Meant for tests. */
46
- key?: VerifyKey;
47
- algorithms?: string[];
48
- }
49
- interface Verifier {
50
- verify(token: string): Promise<AuthUser>;
51
- }
52
- /** Project verified token claims into an `AuthUser`. */
53
- declare function userFromClaims(claims: JWTPayload): AuthUser;
54
- /** Build a verifier for tokens issued by the platform's identity provider. */
55
- declare function createVerifier(options: VerifierOptions): Verifier;
56
- type Env = Record<string, string | undefined>;
57
- /** Build the verifier from `LOGTO_ISSUER`, `LOGTO_AUDIENCE` and `LOGTO_JWKS_URI`. */
58
- declare function verifierFromEnv(env?: Env): Verifier | undefined;
59
- declare function bearerToken(header: string | undefined): string | undefined;
60
- interface AuthenticateOptions {
61
- verifier?: Verifier;
62
- env?: Env;
63
- }
64
- /**
65
- * Require an authenticated caller. On success the user is available through `getUser(c)`.
66
- * With the dev identity enabled no token is verified and every request is the dev user.
67
- */
68
- declare function authenticate(options?: AuthenticateOptions): MiddlewareHandler;
69
- /** The authenticated user of this request. Throws 401 when the route is not authenticated. */
70
- declare function getUser(c: Context): AuthUser;
71
- /** Require every listed permission. Wildcards in the granted set count. */
72
- declare function requirePermission(...codes: string[]): MiddlewareHandler;
73
- /** Require at least one of the listed roles. */
74
- declare function requireRole(...roles: string[]): MiddlewareHandler;
75
- declare module 'hono' {
76
- interface ContextVariableMap {
77
- user: AuthUser;
78
- }
79
- }
80
-
81
- export { type AuthUser as A, ORGANIZATION_AUDIENCE_PREFIX as O, type SupportSession as S, 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, supportFromClaims as s, userFromClaims as u, verifierFromEnv as v };
@@ -1,146 +0,0 @@
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 appBasePath(name) {
97
- return `/apps/${name}/`;
98
- }
99
- function assertValidAppId(value) {
100
- if (!isValidAppId(value)) {
101
- throw new Error(
102
- `Invalid app id ${JSON.stringify(value)}. Expected "app" followed by six characters from [a-z0-9].`
103
- );
104
- }
105
- }
106
- function generateAppId() {
107
- let id = "app";
108
- for (let i = 0; i < 6; i += 1) id += ID_ALPHABET[randomInt(ID_ALPHABET.length)];
109
- return id;
110
- }
111
- function uuidv7(now = Date.now()) {
112
- const bytes = randomBytes(16);
113
- const time = BigInt(now);
114
- bytes[0] = Number(time >> 40n & 0xffn);
115
- bytes[1] = Number(time >> 32n & 0xffn);
116
- bytes[2] = Number(time >> 24n & 0xffn);
117
- bytes[3] = Number(time >> 16n & 0xffn);
118
- bytes[4] = Number(time >> 8n & 0xffn);
119
- bytes[5] = Number(time & 0xffn);
120
- bytes[6] = (bytes[6] ?? 0) & 15 | 112;
121
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
122
- const hex = bytes.toString("hex");
123
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
124
- }
125
-
126
- export {
127
- AppError,
128
- UnauthorizedError,
129
- ForbiddenError,
130
- NotFoundError,
131
- ConflictError,
132
- ValidationError,
133
- toErrorResponse,
134
- errorHandler,
135
- notFoundHandler,
136
- APP_NAME_PATTERN,
137
- APP_ID_PATTERN,
138
- UUID_PATTERN,
139
- isUuid,
140
- isValidAppName,
141
- isValidAppId,
142
- appBasePath,
143
- assertValidAppId,
144
- generateAppId,
145
- uuidv7
146
- };