@barn.dev/sdk 0.0.1-next.20260215045621.1330de7
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 +190 -0
- package/dist/chunk-DQk6qfdC.mjs +18 -0
- package/dist/index.d.mts +210 -0
- package/dist/index.mjs +323 -0
- package/package.json +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2025 Olive Studio Inc.
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, no_symbols) => {
|
|
4
|
+
let target = {};
|
|
5
|
+
for (var name in all) {
|
|
6
|
+
__defProp(target, name, {
|
|
7
|
+
get: all[name],
|
|
8
|
+
enumerable: true
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
if (!no_symbols) {
|
|
12
|
+
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
13
|
+
}
|
|
14
|
+
return target;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
export { __exportAll as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { RequestHandler } from "express";
|
|
3
|
+
import { MiddlewareHandler } from "hono";
|
|
4
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
5
|
+
|
|
6
|
+
//#region src/config.d.ts
|
|
7
|
+
/** Configuration for a database the app connects to */
|
|
8
|
+
interface DatabaseConfig {
|
|
9
|
+
/** Database name as registered in the barn portal */
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
/** Configuration for a barn app */
|
|
13
|
+
interface BarnConfig {
|
|
14
|
+
/** Human-readable name shown in the launcher and portal */
|
|
15
|
+
name: string;
|
|
16
|
+
/** URL-safe slug — becomes the subdomain (e.g. dashboard--acme--prod.barn.dev) */
|
|
17
|
+
slug: string;
|
|
18
|
+
/**
|
|
19
|
+
* Named databases this app connects to.
|
|
20
|
+
* Key is the local alias (used in getConnectionString), value is the database name from the portal.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* databases: {
|
|
24
|
+
* main: { name: "my-postgres-db" },
|
|
25
|
+
* analytics: { name: "analytics-db" },
|
|
26
|
+
* }
|
|
27
|
+
*/
|
|
28
|
+
databases?: Record<string, DatabaseConfig>;
|
|
29
|
+
/** Local development settings */
|
|
30
|
+
dev: {
|
|
31
|
+
/** Command to start the dev server (e.g. "npm run dev") */command: string; /** Port the dev server listens on */
|
|
32
|
+
port: number;
|
|
33
|
+
};
|
|
34
|
+
/** Production deployment settings */
|
|
35
|
+
deploy: {
|
|
36
|
+
/** Port the app listens on in production */port: number; /** Install dependencies (e.g. "npm ci", "pnpm install --frozen-lockfile") */
|
|
37
|
+
install?: string; /** Build command (e.g. "npm run build") */
|
|
38
|
+
build?: string; /** Pre-deploy hook — runs after build, before traffic switch (e.g. DB migrations). Becomes a Fly release_command. */
|
|
39
|
+
predeploy?: string; /** Start command (e.g. "npm start", "node dist/server.js") — required */
|
|
40
|
+
start: string;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** Identity function for type inference — use in barn.json */
|
|
44
|
+
declare function defineConfig(config: BarnConfig): BarnConfig;
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/types.d.ts
|
|
47
|
+
/** Authenticated user identity extracted from barn proxy headers */
|
|
48
|
+
interface BarnUser {
|
|
49
|
+
id: string;
|
|
50
|
+
email: string;
|
|
51
|
+
name: string;
|
|
52
|
+
role: string;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/context.d.ts
|
|
56
|
+
/**
|
|
57
|
+
* Get the authenticated user for the current request.
|
|
58
|
+
*
|
|
59
|
+
* Requires a barn middleware to be installed (e.g. `middleware.hono()`).
|
|
60
|
+
* The middleware reads `X-Barn-User-*` headers injected by the barn proxy
|
|
61
|
+
* and stores them in AsyncLocalStorage so this function works anywhere
|
|
62
|
+
* in the request's async call chain — no need to pass the request object.
|
|
63
|
+
*
|
|
64
|
+
* @throws If called outside a request context (middleware not installed)
|
|
65
|
+
* @throws If barn user headers are missing (request not from barn proxy)
|
|
66
|
+
*/
|
|
67
|
+
declare function getUser(): BarnUser;
|
|
68
|
+
/**
|
|
69
|
+
* Get a database connection string by alias name.
|
|
70
|
+
*
|
|
71
|
+
* Reads from `BARN_DB_{NAME}_URL` environment variable, set automatically
|
|
72
|
+
* by `barn dev` (local) and the deployer (production).
|
|
73
|
+
*
|
|
74
|
+
* Connection strings go through the barn DB proxy — credential rotation
|
|
75
|
+
* in the portal takes effect immediately without redeploying.
|
|
76
|
+
*
|
|
77
|
+
* @param name - The database alias as declared in barn.json `databases`
|
|
78
|
+
* @throws If the environment variable is not set
|
|
79
|
+
*/
|
|
80
|
+
declare function getConnectionString(name: string): string;
|
|
81
|
+
/**
|
|
82
|
+
* Build HMAC-signed identity headers for outgoing requests.
|
|
83
|
+
*
|
|
84
|
+
* Reads the current user from the request context (via middleware)
|
|
85
|
+
* and signs the identity with `BARN_SIGNING_SECRET`. Attach these
|
|
86
|
+
* headers to outgoing requests so receiving servers can verify
|
|
87
|
+
* the request came from a Barn-hosted app.
|
|
88
|
+
*
|
|
89
|
+
* @param secret - Override the signing secret (defaults to `BARN_SIGNING_SECRET` env var)
|
|
90
|
+
* @throws If called outside a request context
|
|
91
|
+
* @throws If no signing secret is available
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```ts
|
|
95
|
+
* import { getAuthHeaders } from "@barn.dev/sdk";
|
|
96
|
+
*
|
|
97
|
+
* const headers = getAuthHeaders();
|
|
98
|
+
* await fetch("https://my-api.com/webhook", { headers });
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
declare function getAuthHeaders(secret?: string): Record<string, string>;
|
|
102
|
+
/**
|
|
103
|
+
* Like `fetch()`, but automatically injects HMAC-signed Barn identity headers.
|
|
104
|
+
*
|
|
105
|
+
* Uses the current request context to identify the user and signs
|
|
106
|
+
* the headers with `BARN_SIGNING_SECRET`.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* import { barnFetch } from "@barn.dev/sdk";
|
|
111
|
+
*
|
|
112
|
+
* const res = await barnFetch("https://my-api.com/webhook", {
|
|
113
|
+
* method: "POST",
|
|
114
|
+
* body: JSON.stringify({ event: "user.created" }),
|
|
115
|
+
* });
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
declare function barnFetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
119
|
+
/**
|
|
120
|
+
* Verify an incoming request was signed by a Barn-hosted app.
|
|
121
|
+
*
|
|
122
|
+
* Checks the HMAC-SHA256 signature and 30-second timestamp freshness.
|
|
123
|
+
* Returns the authenticated user if valid, or `null` if verification fails.
|
|
124
|
+
*
|
|
125
|
+
* @param headers - The incoming request headers (Web `Headers` or Node.js `IncomingHttpHeaders`)
|
|
126
|
+
* @param secret - The signing secret shared with the Barn app
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* import { verifyBarnRequest } from "@barn.dev/sdk";
|
|
131
|
+
*
|
|
132
|
+
* const user = verifyBarnRequest(req.headers, process.env.BARN_SECRET);
|
|
133
|
+
* if (!user) return new Response("Unauthorized", { status: 401 });
|
|
134
|
+
* console.log(`Request from ${user.name} (${user.role})`);
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
declare function verifyBarnRequest(headers: Headers | Record<string, string | string[] | undefined>, secret: string): BarnUser | null;
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/middleware/express.d.ts
|
|
140
|
+
/**
|
|
141
|
+
* Barn middleware for Express / Connect.
|
|
142
|
+
*
|
|
143
|
+
* Extracts `X-Barn-User-*` headers and stores them in AsyncLocalStorage
|
|
144
|
+
* so `getUser()` works anywhere in the request chain.
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* import { middleware } from "@barn.dev/sdk";
|
|
148
|
+
* app.use(middleware.express());
|
|
149
|
+
*/
|
|
150
|
+
declare function express(): RequestHandler;
|
|
151
|
+
//#endregion
|
|
152
|
+
//#region src/middleware/hono.d.ts
|
|
153
|
+
/**
|
|
154
|
+
* Barn middleware for Hono.
|
|
155
|
+
*
|
|
156
|
+
* Extracts `X-Barn-User-*` headers and stores them in AsyncLocalStorage
|
|
157
|
+
* so `getUser()` works anywhere in the request chain.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* import { middleware } from "@barn.dev/sdk";
|
|
161
|
+
* app.use("*", middleware.hono());
|
|
162
|
+
*/
|
|
163
|
+
declare function hono(): MiddlewareHandler;
|
|
164
|
+
//#endregion
|
|
165
|
+
//#region src/middleware/nextjs.d.ts
|
|
166
|
+
/**
|
|
167
|
+
* Barn middleware wrapper for Next.js route handlers.
|
|
168
|
+
*
|
|
169
|
+
* Wraps a route handler to extract `X-Barn-User-*` headers
|
|
170
|
+
* into AsyncLocalStorage so `getUser()` works inside the handler.
|
|
171
|
+
*
|
|
172
|
+
* Note: Next.js middleware.ts runs in a separate execution context from
|
|
173
|
+
* route handlers, so AsyncLocalStorage cannot propagate across that
|
|
174
|
+
* boundary. This wrapper must be applied directly to route handlers.
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* // app/api/hello/route.ts
|
|
178
|
+
* import { middleware, getUser } from "@barn.dev/sdk";
|
|
179
|
+
*
|
|
180
|
+
* export const GET = middleware.nextjs((req: Request) => {
|
|
181
|
+
* const user = getUser();
|
|
182
|
+
* return Response.json({ hello: user.name });
|
|
183
|
+
* });
|
|
184
|
+
*/
|
|
185
|
+
declare function nextjs(handler: (req: Request) => Promise<Response> | Response): (req: Request) => Promise<Response>;
|
|
186
|
+
//#endregion
|
|
187
|
+
//#region src/middleware/node.d.ts
|
|
188
|
+
/**
|
|
189
|
+
* Barn middleware for raw Node.js HTTP servers.
|
|
190
|
+
*
|
|
191
|
+
* Extracts `X-Barn-User-*` headers and stores them in AsyncLocalStorage
|
|
192
|
+
* so `getUser()` works anywhere in the request chain.
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* import { middleware } from "@barn.dev/sdk";
|
|
196
|
+
* import http from "node:http";
|
|
197
|
+
*
|
|
198
|
+
* const barnMw = middleware.node();
|
|
199
|
+
* const server = http.createServer((req, res) => {
|
|
200
|
+
* barnMw(req, res, () => {
|
|
201
|
+
* // getUser() works here
|
|
202
|
+
* });
|
|
203
|
+
* });
|
|
204
|
+
*/
|
|
205
|
+
declare function node(): (req: IncomingMessage, _res: ServerResponse, next: () => void) => void;
|
|
206
|
+
declare namespace index_d_exports {
|
|
207
|
+
export { express, hono, nextjs, node };
|
|
208
|
+
}
|
|
209
|
+
//#endregion
|
|
210
|
+
export { type BarnConfig, type BarnUser, type DatabaseConfig, barnFetch, defineConfig, getAuthHeaders, getConnectionString, getUser, index_d_exports as middleware, verifyBarnRequest };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-DQk6qfdC.mjs";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
//#region src/config.ts
|
|
6
|
+
/** Identity function for type inference — use in barn.json */
|
|
7
|
+
function defineConfig(config) {
|
|
8
|
+
return config;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/context.ts
|
|
13
|
+
/** @internal — used by middleware adapters to store per-request context */
|
|
14
|
+
const barnStore = new AsyncLocalStorage();
|
|
15
|
+
/**
|
|
16
|
+
* Get the authenticated user for the current request.
|
|
17
|
+
*
|
|
18
|
+
* Requires a barn middleware to be installed (e.g. `middleware.hono()`).
|
|
19
|
+
* The middleware reads `X-Barn-User-*` headers injected by the barn proxy
|
|
20
|
+
* and stores them in AsyncLocalStorage so this function works anywhere
|
|
21
|
+
* in the request's async call chain — no need to pass the request object.
|
|
22
|
+
*
|
|
23
|
+
* @throws If called outside a request context (middleware not installed)
|
|
24
|
+
* @throws If barn user headers are missing (request not from barn proxy)
|
|
25
|
+
*/
|
|
26
|
+
function getUser() {
|
|
27
|
+
const ctx = barnStore.getStore();
|
|
28
|
+
if (!ctx) throw new Error("barn getUser() called outside request context. Add barn middleware to your app: app.use(middleware.hono())");
|
|
29
|
+
return {
|
|
30
|
+
id: ctx.userId,
|
|
31
|
+
email: ctx.email,
|
|
32
|
+
name: ctx.name,
|
|
33
|
+
role: ctx.role
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Get a database connection string by alias name.
|
|
38
|
+
*
|
|
39
|
+
* Reads from `BARN_DB_{NAME}_URL` environment variable, set automatically
|
|
40
|
+
* by `barn dev` (local) and the deployer (production).
|
|
41
|
+
*
|
|
42
|
+
* Connection strings go through the barn DB proxy — credential rotation
|
|
43
|
+
* in the portal takes effect immediately without redeploying.
|
|
44
|
+
*
|
|
45
|
+
* @param name - The database alias as declared in barn.json `databases`
|
|
46
|
+
* @throws If the environment variable is not set
|
|
47
|
+
*/
|
|
48
|
+
function getConnectionString(name) {
|
|
49
|
+
const key = `BARN_DB_${name.toUpperCase()}_URL`;
|
|
50
|
+
const url = process.env[key];
|
|
51
|
+
if (!url) throw new Error(`Database "${name}" not configured. Expected env var ${key}. Ensure the database is declared in barn.json and the app was started via barn.`);
|
|
52
|
+
return url;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Build the canonical HMAC payload from identity fields.
|
|
56
|
+
*
|
|
57
|
+
* Uses JSON serialization so that field values containing the delimiter
|
|
58
|
+
* cannot shift field boundaries (prevents delimiter-injection attacks).
|
|
59
|
+
*/
|
|
60
|
+
function buildHmacPayload(timestamp, userId, email, name, role) {
|
|
61
|
+
return JSON.stringify([
|
|
62
|
+
timestamp,
|
|
63
|
+
userId,
|
|
64
|
+
email,
|
|
65
|
+
name,
|
|
66
|
+
role
|
|
67
|
+
]);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Build HMAC-signed identity headers for outgoing requests.
|
|
71
|
+
*
|
|
72
|
+
* Reads the current user from the request context (via middleware)
|
|
73
|
+
* and signs the identity with `BARN_SIGNING_SECRET`. Attach these
|
|
74
|
+
* headers to outgoing requests so receiving servers can verify
|
|
75
|
+
* the request came from a Barn-hosted app.
|
|
76
|
+
*
|
|
77
|
+
* @param secret - Override the signing secret (defaults to `BARN_SIGNING_SECRET` env var)
|
|
78
|
+
* @throws If called outside a request context
|
|
79
|
+
* @throws If no signing secret is available
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```ts
|
|
83
|
+
* import { getAuthHeaders } from "@barn.dev/sdk";
|
|
84
|
+
*
|
|
85
|
+
* const headers = getAuthHeaders();
|
|
86
|
+
* await fetch("https://my-api.com/webhook", { headers });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
function getAuthHeaders(secret) {
|
|
90
|
+
const user = getUser();
|
|
91
|
+
const signingSecret = secret ?? process.env.BARN_SIGNING_SECRET;
|
|
92
|
+
if (!signingSecret) throw new Error("No signing secret available. Set BARN_SIGNING_SECRET env var or pass a secret to getAuthHeaders().");
|
|
93
|
+
const timestamp = Math.floor(Date.now() / 1e3).toString();
|
|
94
|
+
const payload = buildHmacPayload(timestamp, user.id, user.email, user.name, user.role);
|
|
95
|
+
const signature = createHmac("sha256", signingSecret).update(payload).digest("hex");
|
|
96
|
+
return {
|
|
97
|
+
"x-barn-user-id": user.id,
|
|
98
|
+
"x-barn-user-email": user.email,
|
|
99
|
+
"x-barn-user-name": user.name,
|
|
100
|
+
"x-barn-user-role": user.role,
|
|
101
|
+
"x-barn-timestamp": timestamp,
|
|
102
|
+
"x-barn-signature": signature
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Like `fetch()`, but automatically injects HMAC-signed Barn identity headers.
|
|
107
|
+
*
|
|
108
|
+
* Uses the current request context to identify the user and signs
|
|
109
|
+
* the headers with `BARN_SIGNING_SECRET`.
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* ```ts
|
|
113
|
+
* import { barnFetch } from "@barn.dev/sdk";
|
|
114
|
+
*
|
|
115
|
+
* const res = await barnFetch("https://my-api.com/webhook", {
|
|
116
|
+
* method: "POST",
|
|
117
|
+
* body: JSON.stringify({ event: "user.created" }),
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
function barnFetch(input, init) {
|
|
122
|
+
const authHeaders = getAuthHeaders();
|
|
123
|
+
const headers = new Headers(init?.headers);
|
|
124
|
+
for (const [k, v] of Object.entries(authHeaders)) headers.set(k, v);
|
|
125
|
+
return fetch(input, {
|
|
126
|
+
...init,
|
|
127
|
+
headers
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Helper to read a header value from either a `Headers` object
|
|
132
|
+
* or a plain key-value record (e.g. Node.js `req.headers`).
|
|
133
|
+
*/
|
|
134
|
+
function readHeader(headers, name) {
|
|
135
|
+
if (headers instanceof Headers) return headers.get(name);
|
|
136
|
+
const val = headers[name];
|
|
137
|
+
if (Array.isArray(val)) return val[0] ?? null;
|
|
138
|
+
return val ?? null;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Verify an incoming request was signed by a Barn-hosted app.
|
|
142
|
+
*
|
|
143
|
+
* Checks the HMAC-SHA256 signature and 30-second timestamp freshness.
|
|
144
|
+
* Returns the authenticated user if valid, or `null` if verification fails.
|
|
145
|
+
*
|
|
146
|
+
* @param headers - The incoming request headers (Web `Headers` or Node.js `IncomingHttpHeaders`)
|
|
147
|
+
* @param secret - The signing secret shared with the Barn app
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```ts
|
|
151
|
+
* import { verifyBarnRequest } from "@barn.dev/sdk";
|
|
152
|
+
*
|
|
153
|
+
* const user = verifyBarnRequest(req.headers, process.env.BARN_SECRET);
|
|
154
|
+
* if (!user) return new Response("Unauthorized", { status: 401 });
|
|
155
|
+
* console.log(`Request from ${user.name} (${user.role})`);
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
function verifyBarnRequest(headers, secret) {
|
|
159
|
+
const userId = readHeader(headers, "x-barn-user-id");
|
|
160
|
+
const email = readHeader(headers, "x-barn-user-email");
|
|
161
|
+
const name = readHeader(headers, "x-barn-user-name");
|
|
162
|
+
const role = readHeader(headers, "x-barn-user-role");
|
|
163
|
+
const timestampStr = readHeader(headers, "x-barn-timestamp");
|
|
164
|
+
const signature = readHeader(headers, "x-barn-signature");
|
|
165
|
+
if (!userId || !email || !name || !role || !timestampStr || !signature) return null;
|
|
166
|
+
const timestamp = Number.parseInt(timestampStr, 10);
|
|
167
|
+
if (Number.isNaN(timestamp)) return null;
|
|
168
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
169
|
+
if (Math.abs(now - timestamp) > 30) return null;
|
|
170
|
+
const payload = buildHmacPayload(timestampStr, userId, email, name, role);
|
|
171
|
+
const expected = createHmac("sha256", secret).update(payload).digest("hex");
|
|
172
|
+
if (signature.length !== expected.length) return null;
|
|
173
|
+
const a = Buffer.from(signature, "hex");
|
|
174
|
+
const b = Buffer.from(expected, "hex");
|
|
175
|
+
if (a.length !== b.length) return null;
|
|
176
|
+
if (!timingSafeEqual(a, b)) return null;
|
|
177
|
+
return {
|
|
178
|
+
id: userId,
|
|
179
|
+
email,
|
|
180
|
+
name,
|
|
181
|
+
role
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
//#endregion
|
|
186
|
+
//#region src/middleware/express.ts
|
|
187
|
+
/**
|
|
188
|
+
* Barn middleware for Express / Connect.
|
|
189
|
+
*
|
|
190
|
+
* Extracts `X-Barn-User-*` headers and stores them in AsyncLocalStorage
|
|
191
|
+
* so `getUser()` works anywhere in the request chain.
|
|
192
|
+
*
|
|
193
|
+
* @example
|
|
194
|
+
* import { middleware } from "@barn.dev/sdk";
|
|
195
|
+
* app.use(middleware.express());
|
|
196
|
+
*/
|
|
197
|
+
function express() {
|
|
198
|
+
return (req, _res, next) => {
|
|
199
|
+
const userId = req.headers["x-barn-user-id"];
|
|
200
|
+
const email = req.headers["x-barn-user-email"];
|
|
201
|
+
const name = req.headers["x-barn-user-name"];
|
|
202
|
+
const role = req.headers["x-barn-user-role"] ?? "member";
|
|
203
|
+
if (!userId || !email || !name) return next();
|
|
204
|
+
barnStore.run({
|
|
205
|
+
userId,
|
|
206
|
+
email,
|
|
207
|
+
name,
|
|
208
|
+
role
|
|
209
|
+
}, () => next());
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/middleware/hono.ts
|
|
215
|
+
/**
|
|
216
|
+
* Barn middleware for Hono.
|
|
217
|
+
*
|
|
218
|
+
* Extracts `X-Barn-User-*` headers and stores them in AsyncLocalStorage
|
|
219
|
+
* so `getUser()` works anywhere in the request chain.
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* import { middleware } from "@barn.dev/sdk";
|
|
223
|
+
* app.use("*", middleware.hono());
|
|
224
|
+
*/
|
|
225
|
+
function hono() {
|
|
226
|
+
return (c, next) => {
|
|
227
|
+
const userId = c.req.header("x-barn-user-id");
|
|
228
|
+
const email = c.req.header("x-barn-user-email");
|
|
229
|
+
const name = c.req.header("x-barn-user-name");
|
|
230
|
+
const role = c.req.header("x-barn-user-role") ?? "member";
|
|
231
|
+
if (!userId || !email || !name) return next();
|
|
232
|
+
return barnStore.run({
|
|
233
|
+
userId,
|
|
234
|
+
email,
|
|
235
|
+
name,
|
|
236
|
+
role
|
|
237
|
+
}, next);
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
//#endregion
|
|
242
|
+
//#region src/middleware/nextjs.ts
|
|
243
|
+
/**
|
|
244
|
+
* Barn middleware wrapper for Next.js route handlers.
|
|
245
|
+
*
|
|
246
|
+
* Wraps a route handler to extract `X-Barn-User-*` headers
|
|
247
|
+
* into AsyncLocalStorage so `getUser()` works inside the handler.
|
|
248
|
+
*
|
|
249
|
+
* Note: Next.js middleware.ts runs in a separate execution context from
|
|
250
|
+
* route handlers, so AsyncLocalStorage cannot propagate across that
|
|
251
|
+
* boundary. This wrapper must be applied directly to route handlers.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* // app/api/hello/route.ts
|
|
255
|
+
* import { middleware, getUser } from "@barn.dev/sdk";
|
|
256
|
+
*
|
|
257
|
+
* export const GET = middleware.nextjs((req: Request) => {
|
|
258
|
+
* const user = getUser();
|
|
259
|
+
* return Response.json({ hello: user.name });
|
|
260
|
+
* });
|
|
261
|
+
*/
|
|
262
|
+
function nextjs(handler) {
|
|
263
|
+
return async (req) => {
|
|
264
|
+
const userId = req.headers.get("x-barn-user-id");
|
|
265
|
+
const email = req.headers.get("x-barn-user-email");
|
|
266
|
+
const name = req.headers.get("x-barn-user-name");
|
|
267
|
+
const role = req.headers.get("x-barn-user-role") ?? "member";
|
|
268
|
+
if (!userId || !email || !name) return handler(req);
|
|
269
|
+
return barnStore.run({
|
|
270
|
+
userId,
|
|
271
|
+
email,
|
|
272
|
+
name,
|
|
273
|
+
role
|
|
274
|
+
}, () => handler(req));
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
//#endregion
|
|
279
|
+
//#region src/middleware/node.ts
|
|
280
|
+
/**
|
|
281
|
+
* Barn middleware for raw Node.js HTTP servers.
|
|
282
|
+
*
|
|
283
|
+
* Extracts `X-Barn-User-*` headers and stores them in AsyncLocalStorage
|
|
284
|
+
* so `getUser()` works anywhere in the request chain.
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* import { middleware } from "@barn.dev/sdk";
|
|
288
|
+
* import http from "node:http";
|
|
289
|
+
*
|
|
290
|
+
* const barnMw = middleware.node();
|
|
291
|
+
* const server = http.createServer((req, res) => {
|
|
292
|
+
* barnMw(req, res, () => {
|
|
293
|
+
* // getUser() works here
|
|
294
|
+
* });
|
|
295
|
+
* });
|
|
296
|
+
*/
|
|
297
|
+
function node() {
|
|
298
|
+
return (req, _res, next) => {
|
|
299
|
+
const userId = req.headers["x-barn-user-id"];
|
|
300
|
+
const email = req.headers["x-barn-user-email"];
|
|
301
|
+
const name = req.headers["x-barn-user-name"];
|
|
302
|
+
const role = req.headers["x-barn-user-role"] ?? "member";
|
|
303
|
+
if (!userId || !email || !name) return next();
|
|
304
|
+
barnStore.run({
|
|
305
|
+
userId,
|
|
306
|
+
email,
|
|
307
|
+
name,
|
|
308
|
+
role
|
|
309
|
+
}, next);
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region src/middleware/index.ts
|
|
315
|
+
var middleware_exports = /* @__PURE__ */ __exportAll({
|
|
316
|
+
express: () => express,
|
|
317
|
+
hono: () => hono,
|
|
318
|
+
nextjs: () => nextjs,
|
|
319
|
+
node: () => node
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
//#endregion
|
|
323
|
+
export { barnFetch, defineConfig, getAuthHeaders, getConnectionString, getUser, middleware_exports as middleware, verifyBarnRequest };
|
package/package.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@barn.dev/sdk",
|
|
3
|
+
"version": "0.0.1-next.20260215045621.1330de7",
|
|
4
|
+
"description": "Server-side SDK for apps deployed on barn.dev — auth context, database connections, and request signing",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"main": "./dist/index.mjs",
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.mts",
|
|
15
|
+
"import": "./dist/index.mjs",
|
|
16
|
+
"default": "./dist/index.mjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public",
|
|
21
|
+
"registry": "https://registry.npmjs.org/"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/Olive-Studio-Inc/barn.git",
|
|
26
|
+
"directory": "packages/sdk"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://barn.dev",
|
|
29
|
+
"keywords": [
|
|
30
|
+
"barn",
|
|
31
|
+
"barn.dev",
|
|
32
|
+
"internal-tools",
|
|
33
|
+
"sdk",
|
|
34
|
+
"middleware",
|
|
35
|
+
"auth"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@types/express": "^5.0.6",
|
|
42
|
+
"hono": "^4.11.9",
|
|
43
|
+
"tsdown": "^0.20.3",
|
|
44
|
+
"typescript": "^5.9.3"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@types/express": ">=4",
|
|
48
|
+
"express": ">=4",
|
|
49
|
+
"hono": ">=4"
|
|
50
|
+
},
|
|
51
|
+
"peerDependenciesMeta": {
|
|
52
|
+
"hono": {
|
|
53
|
+
"optional": true
|
|
54
|
+
},
|
|
55
|
+
"express": {
|
|
56
|
+
"optional": true
|
|
57
|
+
},
|
|
58
|
+
"@types/express": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsdown",
|
|
64
|
+
"typecheck": "tsc --noEmit"
|
|
65
|
+
}
|
|
66
|
+
}
|