@pepu-chain/sdk 0.2.1 → 0.2.2
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 +1 -2
- package/dist/aa/kernel.cjs +10 -9
- package/dist/aa/kernel.js +5 -4
- package/dist/aa/react-direct.cjs +10 -9
- package/dist/aa/react-direct.cjs.map +1 -1
- package/dist/aa/react-direct.js +5 -4
- package/dist/aa/react-direct.js.map +1 -1
- package/dist/aa/react.cjs +5 -4
- package/dist/aa/react.cjs.map +1 -1
- package/dist/aa/react.js +3 -2
- package/dist/aa/react.js.map +1 -1
- package/dist/aa.cjs +18 -17
- package/dist/aa.js +5 -4
- package/dist/chunk-4GEC7GUU.cjs +283 -0
- package/dist/chunk-4GEC7GUU.cjs.map +1 -0
- package/dist/{chunk-PHM3ZORG.cjs → chunk-4L4CHIXE.cjs} +9 -9
- package/dist/{chunk-PHM3ZORG.cjs.map → chunk-4L4CHIXE.cjs.map} +1 -1
- package/dist/{chunk-A5LP2UCS.cjs → chunk-65Y5UCQ7.cjs} +2 -276
- package/dist/chunk-65Y5UCQ7.cjs.map +1 -0
- package/dist/{chunk-7MNJF2OB.cjs → chunk-DNWWZWUW.cjs} +4 -4
- package/dist/{chunk-7MNJF2OB.cjs.map → chunk-DNWWZWUW.cjs.map} +1 -1
- package/dist/{chunk-D52PADVY.js → chunk-GFKIM7HT.js} +25 -2
- package/dist/chunk-GFKIM7HT.js.map +1 -0
- package/dist/{chunk-IY3ALPUJ.js → chunk-GIZNH65Q.js} +5 -273
- package/dist/chunk-GIZNH65Q.js.map +1 -0
- package/dist/{chunk-WANILJZQ.cjs → chunk-HTCX46RJ.cjs} +25 -2
- package/dist/chunk-HTCX46RJ.cjs.map +1 -0
- package/dist/{chunk-KVG3AYYR.js → chunk-NHPWXIA2.js} +4 -4
- package/dist/{chunk-KVG3AYYR.js.map → chunk-NHPWXIA2.js.map} +1 -1
- package/dist/{chunk-ZB6SVBK4.js → chunk-QIDMFFAQ.js} +4 -4
- package/dist/{chunk-ZB6SVBK4.js.map → chunk-QIDMFFAQ.js.map} +1 -1
- package/dist/{chunk-IB2FSPMJ.js → chunk-QZKUPCUD.js} +3 -3
- package/dist/{chunk-IB2FSPMJ.js.map → chunk-QZKUPCUD.js.map} +1 -1
- package/dist/chunk-RSPAN44L.js +276 -0
- package/dist/chunk-RSPAN44L.js.map +1 -0
- package/dist/{chunk-NVOPDXTA.cjs → chunk-UQH4ZAXD.cjs} +10 -10
- package/dist/{chunk-NVOPDXTA.cjs.map → chunk-UQH4ZAXD.cjs.map} +1 -1
- package/dist/{chunk-BGALSKAF.cjs → chunk-VYMAZVIK.cjs} +4 -4
- package/dist/{chunk-BGALSKAF.cjs.map → chunk-VYMAZVIK.cjs.map} +1 -1
- package/dist/{chunk-F2R473FR.js → chunk-XR5ONV2Y.js} +3 -3
- package/dist/{chunk-F2R473FR.js.map → chunk-XR5ONV2Y.js.map} +1 -1
- package/dist/combo/react.cjs +61 -13
- package/dist/combo/react.cjs.map +1 -1
- package/dist/combo/react.d.cts +14 -2
- package/dist/combo/react.d.ts +14 -2
- package/dist/combo/react.guard.js +1 -1
- package/dist/combo/react.js +58 -11
- package/dist/combo/react.js.map +1 -1
- package/dist/combo.cjs +41 -26
- package/dist/combo.cjs.map +1 -1
- package/dist/combo.d.cts +11 -0
- package/dist/combo.d.ts +11 -0
- package/dist/combo.js +31 -16
- package/dist/combo.js.map +1 -1
- package/dist/index.cjs +10 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/paymaster.cjs +37 -36
- package/dist/paymaster.cjs.map +1 -1
- package/dist/paymaster.js +3 -2
- package/dist/paymaster.js.map +1 -1
- package/dist/react.cjs +4 -3
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +3 -2
- package/dist/react.js.map +1 -1
- package/dist/session/kernel.cjs +18 -17
- package/dist/session/kernel.js +6 -5
- package/package.json +1 -1
- package/dist/chunk-A5LP2UCS.cjs.map +0 -1
- package/dist/chunk-D52PADVY.js.map +0 -1
- package/dist/chunk-IY3ALPUJ.js.map +0 -1
- package/dist/chunk-WANILJZQ.cjs.map +0 -1
package/dist/combo.cjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
/* @pepu-chain/peer-guard */(function(){var p=["@privy-io/node","@zerodev/sdk","@zerodev/permissions","@zerodev/ecdsa-validator"];for(var i=0;i<p.length;i++){try{require.resolve(p[i])}catch(e){if(e&&e.code==="MODULE_NOT_FOUND"){var m="@pepu-chain/sdk/combo needs peer packages that are not installed: @privy-io/node @zerodev/sdk @zerodev/permissions @zerodev/ecdsa-validator. Install with: npm i @privy-io/node @zerodev/sdk @zerodev/permissions @zerodev/ecdsa-validator (or let create-pepu-app scaffold everything).";var x=new Error(m);x.code="PEPU_MISSING_PEER";throw x}}}})();
|
|
3
3
|
|
|
4
|
-
var
|
|
5
|
-
var
|
|
6
|
-
require('./chunk-
|
|
4
|
+
var chunk4L4CHIXE_cjs = require('./chunk-4L4CHIXE.cjs');
|
|
5
|
+
var chunkUQH4ZAXD_cjs = require('./chunk-UQH4ZAXD.cjs');
|
|
6
|
+
require('./chunk-DNWWZWUW.cjs');
|
|
7
7
|
var chunkAJS4UFQX_cjs = require('./chunk-AJS4UFQX.cjs');
|
|
8
|
-
require('./chunk-
|
|
8
|
+
require('./chunk-4GEC7GUU.cjs');
|
|
9
9
|
var chunkRCMKPJZO_cjs = require('./chunk-RCMKPJZO.cjs');
|
|
10
|
-
require('./chunk-
|
|
10
|
+
require('./chunk-HTCX46RJ.cjs');
|
|
11
11
|
require('./chunk-K7JSQPZO.cjs');
|
|
12
|
+
require('./chunk-65Y5UCQ7.cjs');
|
|
12
13
|
var chunkJ3O2ZGG3_cjs = require('./chunk-J3O2ZGG3.cjs');
|
|
13
14
|
require('./chunk-4GINFJO6.cjs');
|
|
14
15
|
var chunkVF3D6KLQ_cjs = require('./chunk-VF3D6KLQ.cjs');
|
|
@@ -41,6 +42,7 @@ async function guard(op, fn) {
|
|
|
41
42
|
function bearerToken(request) {
|
|
42
43
|
return (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
|
|
43
44
|
}
|
|
45
|
+
var PROVISIONING = /* @__PURE__ */ Symbol("wallet-provisioning");
|
|
44
46
|
var nowSeconds = () => Math.floor(Date.now() / 1e3);
|
|
45
47
|
function defaultPublicClient() {
|
|
46
48
|
return viem.createPublicClient({ chain: chunkDPCZJLB3_cjs.pepuMainnet, transport: viem.http(chunkVF3D6KLQ_cjs.resolvePepuEndpoints().rpcUrl) });
|
|
@@ -63,26 +65,38 @@ function createSponsoredSessionRoutes(o) {
|
|
|
63
65
|
revoke: { POST: unset }
|
|
64
66
|
};
|
|
65
67
|
}
|
|
66
|
-
|
|
68
|
+
chunk4L4CHIXE_cjs.buildKernelSessionPolicies({ calls: o.scope.calls, validUntil: 1 });
|
|
67
69
|
let publicClient = o.publicClient;
|
|
68
70
|
const client = () => publicClient ??= defaultPublicClient();
|
|
69
|
-
const
|
|
71
|
+
const wait = { attempts: o.provisioningWait?.attempts ?? 3, delayMs: o.provisioningWait?.delayMs ?? 400 };
|
|
72
|
+
const authenticateOrProvisioning = async (request) => {
|
|
70
73
|
if (o.authenticate) {
|
|
71
74
|
const user = await o.authenticate(request);
|
|
72
75
|
if (!user) throw new chunkYQL7NISX_cjs.PepuAuthError("AUTH_INVALID_TOKEN", "Missing or invalid Privy access token.");
|
|
73
76
|
return user;
|
|
74
77
|
}
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
const privy = o.privy ?? chunk45KSZH26_cjs.createPrivyServer();
|
|
79
|
+
for (let attempt = 0; ; attempt++) {
|
|
80
|
+
const auth = await chunk45KSZH26_cjs.requireUser(request, { privy });
|
|
81
|
+
if (!auth.ok) return auth.response;
|
|
82
|
+
if (auth.user.address) return { userId: auth.user.userId, ownerAddress: auth.user.address };
|
|
83
|
+
if (attempt >= wait.attempts) return PROVISIONING;
|
|
84
|
+
await new Promise((resolve) => setTimeout(resolve, wait.delayMs * (attempt + 1)));
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const authenticate = async (request) => {
|
|
88
|
+
const user = await authenticateOrProvisioning(request);
|
|
89
|
+
if (user === PROVISIONING) {
|
|
90
|
+
throw new chunkYQL7NISX_cjs.PepuAuthError(
|
|
91
|
+
"WALLET_NOT_PROVISIONED",
|
|
92
|
+
"Your wallet is still being set up. This usually takes a few seconds; retrying.",
|
|
93
|
+
{ status: 409, retryable: true }
|
|
94
|
+
);
|
|
81
95
|
}
|
|
82
|
-
return
|
|
96
|
+
return user;
|
|
83
97
|
};
|
|
84
98
|
const minutes = () => o.minutes ?? chunkIG7RSL2Y_cjs.resolveSessionMinutes(process.env.SESSION_DURATION_MINUTES);
|
|
85
|
-
const policiesFor = (validUntil) =>
|
|
99
|
+
const policiesFor = (validUntil) => chunk4L4CHIXE_cjs.buildKernelSessionPolicies({ calls: o.scope.calls, validUntil });
|
|
86
100
|
return {
|
|
87
101
|
prepare: {
|
|
88
102
|
POST: (request) => guard("combo prepare", async () => {
|
|
@@ -91,11 +105,11 @@ function createSponsoredSessionRoutes(o) {
|
|
|
91
105
|
const { userId, ownerAddress } = user;
|
|
92
106
|
const mins = minutes();
|
|
93
107
|
const validUntil = chunkIG7RSL2Y_cjs.sessionExpiry(nowSeconds(), mins);
|
|
94
|
-
const key =
|
|
108
|
+
const key = chunk4L4CHIXE_cjs.generateSessionKey();
|
|
95
109
|
const policies = policiesFor(validUntil);
|
|
96
110
|
const [kernelAddress, permissionId] = await Promise.all([
|
|
97
|
-
|
|
98
|
-
|
|
111
|
+
chunkUQH4ZAXD_cjs.getKernelAddress(client(), ownerAddress),
|
|
112
|
+
chunk4L4CHIXE_cjs.expectedPermissionId({ publicClient: client(), sessionKeyAddress: key.address, policies })
|
|
99
113
|
]);
|
|
100
114
|
const record = {
|
|
101
115
|
userId,
|
|
@@ -146,10 +160,11 @@ function createSponsoredSessionRoutes(o) {
|
|
|
146
160
|
},
|
|
147
161
|
status: {
|
|
148
162
|
GET: (request) => guard("combo status", async () => {
|
|
149
|
-
const user = await
|
|
163
|
+
const user = await authenticateOrProvisioning(request);
|
|
150
164
|
if (user instanceof Response) return user;
|
|
165
|
+
if (user === PROVISIONING) return json({ active: false, provisioning: true });
|
|
151
166
|
const record = await o.store.get(user.userId);
|
|
152
|
-
if (!record || !
|
|
167
|
+
if (!record || !chunk4L4CHIXE_cjs.isLive(record, nowSeconds())) return json({ active: false });
|
|
153
168
|
return json({
|
|
154
169
|
active: true,
|
|
155
170
|
validUntil: record.validUntil,
|
|
@@ -165,7 +180,7 @@ function createSponsoredSessionRoutes(o) {
|
|
|
165
180
|
const user = await authenticate(request);
|
|
166
181
|
if (user instanceof Response) return user;
|
|
167
182
|
const record = await o.store.get(user.userId);
|
|
168
|
-
if (!record || !record.approval || !
|
|
183
|
+
if (!record || !record.approval || !chunk4L4CHIXE_cjs.isLive(record, nowSeconds())) {
|
|
169
184
|
throw new chunkYQL7NISX_cjs.PepuSessionError("SESSION_NONE", "No active session. Start one first.");
|
|
170
185
|
}
|
|
171
186
|
let input;
|
|
@@ -192,12 +207,12 @@ function createSponsoredSessionRoutes(o) {
|
|
|
192
207
|
}
|
|
193
208
|
const privyToken = o.forwardPrivyToken === false ? "" : bearerToken(request);
|
|
194
209
|
try {
|
|
195
|
-
const account = await
|
|
210
|
+
const account = await chunk4L4CHIXE_cjs.loadKernelSessionAccount({
|
|
196
211
|
publicClient: client(),
|
|
197
212
|
approval: record.approval,
|
|
198
213
|
sessionPrivateKey: record.sessionPrivateKey
|
|
199
214
|
});
|
|
200
|
-
const kernel =
|
|
215
|
+
const kernel = chunkUQH4ZAXD_cjs.createPepuSponsoredClient({
|
|
201
216
|
account,
|
|
202
217
|
publicClient: client(),
|
|
203
218
|
...o.endpoints?.bundlerUrl !== void 0 ? { bundlerUrl: o.endpoints.bundlerUrl } : {},
|
|
@@ -205,7 +220,7 @@ function createSponsoredSessionRoutes(o) {
|
|
|
205
220
|
...o.endpoints?.paymasterToken !== void 0 ? { paymasterToken: o.endpoints.paymasterToken } : {},
|
|
206
221
|
...privyToken ? { paymasterContext: chunkRCMKPJZO_cjs.buildPaymasterContext({ privyAccessToken: privyToken }) } : {}
|
|
207
222
|
});
|
|
208
|
-
const result = await
|
|
223
|
+
const result = await chunkUQH4ZAXD_cjs.sendSponsored({ client: kernel, calls });
|
|
209
224
|
const actions = record.actions + (result.success ? 1 : 0);
|
|
210
225
|
if (result.success) await o.store.set({ ...record, actions });
|
|
211
226
|
const out = {
|
|
@@ -247,11 +262,11 @@ function assertCallsInScope(scope, calls) {
|
|
|
247
262
|
|
|
248
263
|
Object.defineProperty(exports, "createMemoryStore", {
|
|
249
264
|
enumerable: true,
|
|
250
|
-
get: function () { return
|
|
265
|
+
get: function () { return chunk4L4CHIXE_cjs.createMemoryStore; }
|
|
251
266
|
});
|
|
252
267
|
Object.defineProperty(exports, "isLive", {
|
|
253
268
|
enumerable: true,
|
|
254
|
-
get: function () { return
|
|
269
|
+
get: function () { return chunk4L4CHIXE_cjs.isLive; }
|
|
255
270
|
});
|
|
256
271
|
Object.defineProperty(exports, "resolveSessionMinutes", {
|
|
257
272
|
enumerable: true,
|
package/dist/combo.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/combo/server.ts"],"names":["assertServerOnly","toPepuError","PepuError","PepuChainError","toErrorResponse","createPublicClient","pepuMainnet","http","resolvePepuEndpoints","PepuConfigError","buildKernelSessionPolicies","PepuAuthError","requireUser","createPrivyServer","resolveSessionMinutes","sessionExpiry","generateSessionKey","getKernelAddress","expectedPermissionId","describeKernelSessionScope","PepuPolicyError","PepuSessionError","checkApproval","isLive","loadKernelSessionAccount","createPepuSponsoredClient","buildPaymasterContext","sendSponsored","normalizeCalls","isCallInScope"],"mappings":";;;;;;;;;;;;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WAAA;AAAA,YACpB;AAAA,WACF;AACA,UAAA,OAAO,KAAK,GAAG,CAAA;AAAA,QACjB,CAAA,SAAE;AACA,UAAA,MAAM,CAAA,CAAE,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAAA,QAClC;AAAA,MACF,CAAC;AAAA,KACL;AAAA,IAEA,MAAA,EAAQ;AAAA,MACN,IAAA,EAAM,CAAC,OAAA,KACL,KAAA,CAAM,gBAAgB,YAAY;AAChC,QAAA,MAAM,IAAA,GAAO,MAAM,YAAA,CAAa,OAAO,CAAA;AACvC,QAAA,IAAI,IAAA,YAAgB,UAAU,OAAO,IAAA;AACrC,QAAA,MAAM,CAAA,CAAE,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAChC,QAAA,OAAO,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAA,EAAO,CAAA;AAAA,MAC/B,CAAC;AAAA;AACL,GACF;AACF;AAUO,SAAS,kBAAA,CAAmB,OAA0C,KAAA,EAA8B;AACzG,EAAA,KAAA,MAAW,CAAA,IAAKC,gCAAA,CAAe,KAAK,CAAA,EAAG;AACrC,IAAA,IAAI,CAACC,+BAAA,CAAc,KAAA,EAAO,CAAC,CAAA,EAAG;AAC5B,MAAA,MAAM,IAAIT,iCAAA,CAAgB,iBAAA,EAAmB,sCAAA,EAAwC;AAAA,QACnF,MAAA,EAAQ,GAAA;AAAA,QACR,IAAA,EAAM;AAAA,OACP,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"combo.cjs","sourcesContent":["import type { PrivyClient } from \"@privy-io/node\";\nimport { createPublicClient, http } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\nimport type { SponsoredActResult } from \"./types.js\";\nimport { createPepuSponsoredClient, sendSponsored } from \"../aa/kernel.js\";\nimport { normalizeCalls } from \"../aa/calls.js\";\nimport type { Call } from \"../aa/types.js\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { resolvePepuEndpoints } from \"../endpoints.js\";\nimport { buildPaymasterContext } from \"../erc7677.js\";\nimport {\n PepuAuthError,\n PepuChainError,\n PepuConfigError,\n PepuError,\n PepuPolicyError,\n PepuSessionError,\n toErrorResponse,\n toPepuError,\n} from \"../errors.js\";\nimport { assertServerOnly } from \"../internal/assert-server.js\";\nimport { createPrivyServer, requireUser } from \"../privy/server.js\";\nimport { resolveSessionMinutes, sessionExpiry } from \"../session/policy.js\";\nimport {\n buildKernelSessionPolicies,\n checkApproval,\n describeKernelSessionScope,\n expectedPermissionId,\n generateSessionKey,\n getKernelAddress,\n isCallInScope,\n loadKernelSessionAccount,\n} from \"../session/kernel.js\";\nimport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nimport { isLive } from \"../session/store.js\";\nimport type { SessionRecord, SessionStore } from \"../session/store.js\";\n\nassertServerOnly(\"@pepu-chain/sdk/combo\");\n\n/**\n * `@pepu-chain/sdk/combo` (server): the combined flow. Google sign-in (Privy),\n * a ONE-TIME on-chain session, and sponsored gas. Route factories for the\n * Kernel session lifecycle: prepare, activate, status, act, revoke.\n *\n * Extracted from templates/sponsored-session-app/app/api/session/* and\n * lib/{kernel,session-auth}.ts.\n *\n * Trust model: the chain, not these routes, enforces scope. The owner's single\n * EIP-712 signature enables a permission whose call policy (targets,\n * selectors, zero value) and timestamp policy the Kernel account verifies on\n * every UserOperation. The checks here only fail fast.\n *\n * Optional peers: `@privy-io/node`, `@zerodev/*`.\n */\n\nexport { createMemoryStore, isLive } from \"../session/store.js\";\nexport type { SessionRecord, SessionStore } from \"../session/store.js\";\nexport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nexport type { SponsoredActResult } from \"./types.js\";\n/** Session length from `SESSION_DURATION_MINUTES` (default 15, clamped to 1..1440), the same rule the routes use. */\nexport { resolveSessionMinutes } from \"../session/policy.js\";\n\n/** The authenticated caller of a combo route. */\nexport interface ComboUser {\n userId: string;\n /** The user's Privy embedded wallet: the owner of their Kernel account. From Privy, never the request. */\n ownerAddress: Address;\n}\n\n/** Authenticate a request. Throw a `PepuError` (or return `null`) when it is not valid. */\nexport type ComboAuthenticate = (request: Request) => Promise<ComboUser | null>;\n\n/** Options for {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutesOptions<I> {\n /** What the session may call. Enforced on-chain by the call policy. */\n scope: {\n calls: readonly KernelSessionCall[];\n /** Env variable named in the `CONFIG_MISSING_ENV` message when a call target is empty (unset). */\n targetEnv?: string;\n };\n /**\n * Where session records (including the session private key) live. Use\n * `createMemoryStore()` for development only: production needs a persistent\n * store with the key encrypted at rest.\n */\n store: SessionStore;\n /**\n * Bundler and paymaster. The bundler defaults to env `PEPU_BUNDLER_URL`, then the hosted bundler. The paymaster\n * needs a complete ERC-7677 URL (env `PEPU_PAYMASTER_URL`, or `paymasterUrl`) or a project `paymasterToken`\n * (built against the hosted paymaster base).\n */\n endpoints?: { bundlerUrl?: string; paymasterUrl?: string; paymasterToken?: string };\n /**\n * Forward the caller's Privy access token (the request's `Authorization: Bearer`) to the paymaster as ERC-7677\n * `context.privyAccessToken`. The v2 FREE TIER requires it; a project paying from its own deposit does not.\n * Default `true`. Set `false` if your paymaster URL is not a PEPU policy service you trust with the token.\n */\n forwardPrivyToken?: boolean;\n /** Session length. Default env `SESSION_DURATION_MINUTES`, then 15; clamped to 1..1440. */\n minutes?: number;\n /** The one action users take with their session. */\n act: {\n /** Validate the client body. Throw to reject with 400. */\n parse(body: unknown): I;\n /** The calls to send. Each is re-checked against `scope` before sponsoring. */\n buildCalls(input: I, ctx: { kernelAddress: Address; ownerAddress: Address }): Call[];\n };\n /** Privy client for the default authentication. Default `createPrivyServer()`. */\n privy?: PrivyClient;\n /**\n * Custom authentication. Default: B1's `requireUser` (verifies the Privy\n * bearer token and reads the user's embedded wallet from Privy).\n */\n authenticate?: ComboAuthenticate;\n /** Chain reads. Default: viem on the PEPU RPC (`PEPU_RPC_URL` aware). */\n publicClient?: PublicClient;\n}\n\n/** The five route handlers returned by {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutes {\n prepare: { POST(request: Request): Promise<Response> };\n activate: { POST(request: Request): Promise<Response> };\n status: { GET(request: Request): Promise<Response> };\n act: { POST(request: Request): Promise<Response> };\n revoke: { POST(request: Request): Promise<Response> };\n}\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n}\n\n/** Anything unclassified that reaches a route is an upstream failure, not our 500. */\nfunction upstream(e: unknown, op: string): PepuError {\n const err = toPepuError(e, { op });\n if (err.code === \"UNKNOWN\" && !(e instanceof PepuError)) {\n return new PepuChainError(\"UNKNOWN\", err.message, { status: 502, cause: e });\n }\n return err;\n}\n\nasync function guard(op: string, fn: () => Promise<Response>): Promise<Response> {\n try {\n return await fn();\n } catch (e) {\n return toErrorResponse(upstream(e, op));\n }\n}\n\n/** The bearer token on a request, or `\"\"`. */\nfunction bearerToken(request: Request): string {\n return (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer\\s+/i, \"\").trim();\n}\n\nconst nowSeconds = (): number => Math.floor(Date.now() / 1000);\n\nfunction defaultPublicClient(): PublicClient {\n return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) }) as PublicClient;\n}\n\n/**\n * Route handlers for the Kernel session lifecycle.\n *\n * - `prepare.POST`: the server creates a fresh session key and decides the\n * expiry. The private key stays on the server; the response carries only the\n * key's address, the expiry and the scope, so the browser can ask the owner\n * for the ONE signature that grants exactly that. Calling it again replaces\n * any pending or active session (the old key is dropped).\n * - `activate.POST` `{ approval }`: checks the approval is for this user's\n * smart account and for exactly the key, scope and expiry issued in\n * `prepare`, then stores it. 409 `SESSION_NONE` when nothing is pending,\n * 410 `SESSION_EXPIRED` for an expired offer, 400 `SESSION_APPROVAL_MISMATCH`.\n * - `status.GET`: `{ active: false }` or `{ active: true, validUntil, ... }`.\n * Never returns the session key or approval.\n * - `act.POST`: signs ONE sponsored UserOperation with the session key. 409\n * `SESSION_NONE` without a live session, 429 while another action runs.\n * - `revoke.POST`: deletes the session key and approval from the server, so\n * the app can no longer act, immediately. It does NOT uninstall the\n * permission on-chain: that grant stays valid until its expiry, but only the\n * deleted key can use it and only within the scope. An on-chain uninstall is\n * an owner-signed call to the user's own account, which a paymaster\n * destination allowlist rightly does not sponsor.\n *\n * Gas: the paymaster policy service reserves worst-case cost per operation:\n * about 20.5 PEPU for a session's first operation and about 6.9 PEPU for later\n * ones (`SESSION_GAS_RESERVATION_PEPU`). Size spend caps above that. Fees come\n * from the chain with 20% headroom.\n *\n * @example\n * // lib/session-routes.ts\n * export const routes = createSponsoredSessionRoutes({\n * scope: { calls: [{ target: tapScore, abi: tapScoreAbi, functionName: \"tap\" }] },\n * store: createMemoryStore(), // DEV ONLY\n * act: {\n * parse: () => ({}),\n * buildCalls: () => [{ to: tapScore, abi: tapScoreAbi, functionName: \"tap\" }],\n * },\n * });\n * // app/api/session/prepare/route.ts: export const { POST } = routes.prepare;\n */\nexport function createSponsoredSessionRoutes<I>(o: SponsoredSessionRoutesOptions<I>): SponsoredSessionRoutes {\n // A call whose target is empty or undefined (an unset env variable) is \"not configured yet\":\n // every route then answers CONFIG_MISSING_ENV at request time. A malformed non-empty scope\n // still fails at startup, not on the first request.\n const unconfigured = o.scope.calls.some((c) => !c.target || String(c.target).trim() === \"\");\n if (unconfigured) {\n const unset = async (): Promise<Response> =>\n toErrorResponse(\n new PepuConfigError(\n \"CONFIG_MISSING_ENV\",\n `${o.scope.targetEnv ?? \"A session target contract address\"} is not set to a valid address. See .env.example.`,\n { hint: \"Set it and restart the server.\" },\n ),\n );\n return {\n prepare: { POST: unset },\n activate: { POST: unset },\n status: { GET: unset },\n act: { POST: unset },\n revoke: { POST: unset },\n };\n }\n buildKernelSessionPolicies({ calls: o.scope.calls, validUntil: 1 });\n let publicClient = o.publicClient;\n const client = (): PublicClient => (publicClient ??= defaultPublicClient());\n\n const authenticate = async (request: Request): Promise<ComboUser | Response> => {\n if (o.authenticate) {\n const user = await o.authenticate(request);\n if (!user) throw new PepuAuthError(\"AUTH_INVALID_TOKEN\", \"Missing or invalid Privy access token.\");\n return user;\n }\n const auth = await requireUser(request, { privy: o.privy ?? createPrivyServer() });\n if (!auth.ok) return auth.response;\n if (!auth.user.address) {\n throw new PepuAuthError(\"WALLET_NOT_PROVISIONED\", \"No embedded wallet yet. Create it first (ensure-wallet route).\", {\n status: 409,\n });\n }\n return { userId: auth.user.userId, ownerAddress: auth.user.address };\n };\n\n const minutes = (): number => o.minutes ?? resolveSessionMinutes(process.env.SESSION_DURATION_MINUTES);\n const policiesFor = (validUntil: number) => buildKernelSessionPolicies({ calls: o.scope.calls, validUntil });\n\n return {\n prepare: {\n POST: (request) =>\n guard(\"combo prepare\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const { userId, ownerAddress } = user;\n const mins = minutes();\n const validUntil = sessionExpiry(nowSeconds(), mins);\n const key = generateSessionKey();\n const policies = policiesFor(validUntil);\n const [kernelAddress, permissionId] = await Promise.all([\n getKernelAddress(client(), ownerAddress),\n expectedPermissionId({ publicClient: client(), sessionKeyAddress: key.address, policies }),\n ]);\n const record: SessionRecord = {\n userId,\n ownerAddress,\n kernelAddress,\n sessionPrivateKey: key.privateKey,\n sessionKeyAddress: key.address,\n permissionId,\n validUntil,\n approval: null,\n actions: 0,\n };\n await o.store.set(record);\n return json({\n ownerAddress,\n kernelAddress,\n sessionKeyAddress: key.address,\n validUntil,\n minutes: mins,\n scope: describeKernelSessionScope({ calls: o.scope.calls, validUntil }),\n });\n }),\n },\n\n activate: {\n POST: (request) =>\n guard(\"combo activate\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const body = (await request.json().catch(() => null)) as { approval?: unknown } | null;\n if (typeof body?.approval !== \"string\") {\n throw new PepuPolicyError(\"UNKNOWN\", \"Missing approval.\", { status: 400, hint: \"Send { approval }.\" });\n }\n const record = await o.store.get(user.userId);\n if (!record || record.approval !== null) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No pending session. Start again.\");\n }\n if (nowSeconds() >= record.validUntil) {\n await o.store.delete(record.userId);\n throw new PepuSessionError(\"SESSION_EXPIRED\", \"The session offer expired. Start again.\");\n }\n const check = checkApproval(body.approval, {\n kernelAddress: record.kernelAddress,\n permissionId: record.permissionId,\n });\n if (!check.ok) throw new PepuSessionError(\"SESSION_APPROVAL_MISMATCH\", check.reason, { status: 400 });\n await o.store.set({ ...record, approval: body.approval });\n return json({ active: true, validUntil: record.validUntil });\n }),\n },\n\n status: {\n GET: (request) =>\n guard(\"combo status\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const record = await o.store.get(user.userId);\n if (!record || !isLive(record, nowSeconds())) return json({ active: false });\n return json({\n active: true,\n validUntil: record.validUntil,\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n sessionKeyAddress: record.sessionKeyAddress,\n actions: record.actions,\n });\n }),\n },\n\n act: {\n POST: (request) =>\n guard(\"combo act\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const record = await o.store.get(user.userId);\n if (!record || !record.approval || !isLive(record, nowSeconds())) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No active session. Start one first.\");\n }\n\n let input: I;\n try {\n input = o.act.parse(await request.json().catch(() => ({})));\n } catch (e) {\n throw new PepuPolicyError(\"UNKNOWN\", e instanceof Error ? e.message : \"Invalid request body.\", {\n status: 400,\n hint: \"Fix the request body.\",\n cause: e,\n });\n }\n const calls = o.act.buildCalls(input, {\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n });\n // Fail fast; the chain is the real enforcement (see the file comment).\n assertCallsInScope(describeKernelSessionScope({ calls: o.scope.calls, validUntil: record.validUntil }), calls);\n\n if (!(await o.store.tryLock(user.userId))) {\n throw new PepuChainError(\"UNKNOWN\", \"An action is already in flight.\", {\n status: 429,\n retryable: true,\n hint: \"Wait for the current action to finish.\",\n });\n }\n const privyToken = o.forwardPrivyToken === false ? \"\" : bearerToken(request);\n try {\n const account = await loadKernelSessionAccount({\n publicClient: client(),\n approval: record.approval,\n sessionPrivateKey: record.sessionPrivateKey,\n });\n const kernel = createPepuSponsoredClient({\n account,\n publicClient: client(),\n ...(o.endpoints?.bundlerUrl !== undefined ? { bundlerUrl: o.endpoints.bundlerUrl } : {}),\n ...(o.endpoints?.paymasterUrl !== undefined ? { paymasterUrl: o.endpoints.paymasterUrl } : {}),\n ...(o.endpoints?.paymasterToken !== undefined ? { paymasterToken: o.endpoints.paymasterToken } : {}),\n ...(privyToken ? { paymasterContext: buildPaymasterContext({ privyAccessToken: privyToken }) } : {}),\n });\n const result = await sendSponsored({ client: kernel, calls });\n const actions = record.actions + (result.success ? 1 : 0);\n if (result.success) await o.store.set({ ...record, actions });\n const out: SponsoredActResult = {\n userOpHash: result.userOpHash,\n transactionHash: result.transactionHash,\n kernelAddress: record.kernelAddress,\n success: result.success,\n paymaster: result.paymaster,\n actualGasCostWei: result.actualGasCostWei.toString(),\n explorerUrl: result.explorerUrl,\n actions,\n };\n return json(out);\n } finally {\n await o.store.unlock(user.userId);\n }\n }),\n },\n\n revoke: {\n POST: (request) =>\n guard(\"combo revoke\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n await o.store.delete(user.userId);\n return json({ active: false });\n }),\n },\n };\n}\n\n/**\n * Throws `POLICY_UNSCOPED` (403) unless every call targets an allowed contract\n * and function selector with a value within the limit. Pure; used by the act\n * route and exported for custom routes.\n *\n * @example\n * assertCallsInScope(describeKernelSessionScope({ calls, validUntil }), [{ to, abi, functionName: \"tap\" }]);\n */\nexport function assertCallsInScope(scope: Pick<KernelSessionScope, \"calls\">, calls: readonly Call[]): void {\n for (const c of normalizeCalls(calls)) {\n if (!isCallInScope(scope, c)) {\n throw new PepuPolicyError(\"POLICY_UNSCOPED\", \"A call is outside the session scope.\", {\n status: 403,\n hint: \"Only the contracts and functions the user approved can be called.\",\n });\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/combo/server.ts"],"names":["assertServerOnly","toPepuError","PepuError","PepuChainError","toErrorResponse","createPublicClient","pepuMainnet","http","resolvePepuEndpoints","PepuConfigError","buildKernelSessionPolicies","PepuAuthError","createPrivyServer","requireUser","resolveSessionMinutes","sessionExpiry","generateSessionKey","getKernelAddress","expectedPermissionId","describeKernelSessionScope","PepuPolicyError","PepuSessionError","checkApproval","isLive","loadKernelSessionAccount","createPepuSponsoredClient","buildPaymasterContext","sendSponsored","normalizeCalls","isCallInScope"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqCAA,kCAAA,CAAiB,uBAAuB,CAAA;AAkGxC,SAAS,IAAA,CAAK,IAAA,EAAe,MAAA,GAAS,GAAA,EAAe;AACnD,EAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA,EAAG,EAAE,MAAA,EAAQ,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,IAAsB,CAAA;AACvG;AAGA,SAAS,QAAA,CAAS,GAAY,EAAA,EAAuB;AACnD,EAAA,MAAM,GAAA,GAAMC,6BAAA,CAAY,CAAA,EAAG,EAAE,IAAI,CAAA;AACjC,EAAA,IAAI,GAAA,CAAI,IAAA,KAAS,SAAA,IAAa,EAAE,aAAaC,2BAAA,CAAA,EAAY;AACvD,IAAA,OAAO,IAAIC,gCAAA,CAAe,SAAA,EAAW,GAAA,CAAI,OAAA,EAAS,EAAE,MAAA,EAAQ,GAAA,EAAK,KAAA,EAAO,CAAA,EAAG,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,GAAA;AACT;AAEA,eAAe,KAAA,CAAM,IAAY,EAAA,EAAgD;AAC/E,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,EAAA,EAAG;AAAA,EAClB,SAAS,CAAA,EAAG;AACV,IAAA,OAAOC,iCAAA,CAAgB,QAAA,CAAS,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,EACxC;AACF;AAGA,SAAS,YAAY,OAAA,EAA0B;AA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A;AAAA,QACjB,CAAA,SAAE;AACA,UAAA,MAAM,CAAA,CAAE,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAAA,QAClC;AAAA,MACF,CAAC;AAAA,KACL;AAAA,IAEA,MAAA,EAAQ;AAAA,MACN,IAAA,EAAM,CAAC,OAAA,KACL,KAAA,CAAM,gBAAgB,YAAY;AAChC,QAAA,MAAM,IAAA,GAAO,MAAM,YAAA,CAAa,OAAO,CAAA;AACvC,QAAA,IAAI,IAAA,YAAgB,UAAU,OAAO,IAAA;AACrC,QAAA,MAAM,CAAA,CAAE,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAChC,QAAA,OAAO,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAA,EAAO,CAAA;AAAA,MAC/B,CAAC;AAAA;AACL,GACF;AACF;AAUO,SAAS,kBAAA,CAAmB,OAA0C,KAAA,EAA8B;AACzG,EAAA,KAAA,MAAW,CAAA,IAAKC,gCAAA,CAAe,KAAK,CAAA,EAAG;AACrC,IAAA,IAAI,CAACC,+BAAA,CAAc,KAAA,EAAO,CAAC,CAAA,EAAG;AAC5B,MAAA,MAAM,IAAIT,iCAAA,CAAgB,iBAAA,EAAmB,sCAAA,EAAwC;AAAA,QACnF,MAAA,EAAQ,GAAA;AAAA,QACR,IAAA,EAAM;AAAA,OACP,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"combo.cjs","sourcesContent":["import type { PrivyClient } from \"@privy-io/node\";\nimport { createPublicClient, http } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\nimport type { SponsoredActResult } from \"./types.js\";\nimport { createPepuSponsoredClient, sendSponsored } from \"../aa/kernel.js\";\nimport { normalizeCalls } from \"../aa/calls.js\";\nimport type { Call } from \"../aa/types.js\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { resolvePepuEndpoints } from \"../endpoints.js\";\nimport { buildPaymasterContext } from \"../erc7677.js\";\nimport {\n PepuAuthError,\n PepuChainError,\n PepuConfigError,\n PepuError,\n PepuPolicyError,\n PepuSessionError,\n toErrorResponse,\n toPepuError,\n} from \"../errors.js\";\nimport { assertServerOnly } from \"../internal/assert-server.js\";\nimport { createPrivyServer, requireUser } from \"../privy/server.js\";\nimport { resolveSessionMinutes, sessionExpiry } from \"../session/policy.js\";\nimport {\n buildKernelSessionPolicies,\n checkApproval,\n describeKernelSessionScope,\n expectedPermissionId,\n generateSessionKey,\n getKernelAddress,\n isCallInScope,\n loadKernelSessionAccount,\n} from \"../session/kernel.js\";\nimport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nimport { isLive } from \"../session/store.js\";\nimport type { SessionRecord, SessionStore } from \"../session/store.js\";\n\nassertServerOnly(\"@pepu-chain/sdk/combo\");\n\n/**\n * `@pepu-chain/sdk/combo` (server): the combined flow. Google sign-in (Privy),\n * a ONE-TIME on-chain session, and sponsored gas. Route factories for the\n * Kernel session lifecycle: prepare, activate, status, act, revoke.\n *\n * Extracted from templates/sponsored-session-app/app/api/session/* and\n * lib/{kernel,session-auth}.ts.\n *\n * Trust model: the chain, not these routes, enforces scope. The owner's single\n * EIP-712 signature enables a permission whose call policy (targets,\n * selectors, zero value) and timestamp policy the Kernel account verifies on\n * every UserOperation. The checks here only fail fast.\n *\n * Optional peers: `@privy-io/node`, `@zerodev/*`.\n */\n\nexport { createMemoryStore, isLive } from \"../session/store.js\";\nexport type { SessionRecord, SessionStore } from \"../session/store.js\";\nexport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nexport type { SponsoredActResult } from \"./types.js\";\n/** Session length from `SESSION_DURATION_MINUTES` (default 15, clamped to 1..1440), the same rule the routes use. */\nexport { resolveSessionMinutes } from \"../session/policy.js\";\n\n/** The authenticated caller of a combo route. */\nexport interface ComboUser {\n userId: string;\n /** The user's Privy embedded wallet: the owner of their Kernel account. From Privy, never the request. */\n ownerAddress: Address;\n}\n\n/** Authenticate a request. Throw a `PepuError` (or return `null`) when it is not valid. */\nexport type ComboAuthenticate = (request: Request) => Promise<ComboUser | null>;\n\n/** Options for {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutesOptions<I> {\n /** What the session may call. Enforced on-chain by the call policy. */\n scope: {\n calls: readonly KernelSessionCall[];\n /** Env variable named in the `CONFIG_MISSING_ENV` message when a call target is empty (unset). */\n targetEnv?: string;\n };\n /**\n * Where session records (including the session private key) live. Use\n * `createMemoryStore()` for development only: production needs a persistent\n * store with the key encrypted at rest.\n */\n store: SessionStore;\n /**\n * Bundler and paymaster. The bundler defaults to env `PEPU_BUNDLER_URL`, then the hosted bundler. The paymaster\n * needs a complete ERC-7677 URL (env `PEPU_PAYMASTER_URL`, or `paymasterUrl`) or a project `paymasterToken`\n * (built against the hosted paymaster base).\n */\n endpoints?: { bundlerUrl?: string; paymasterUrl?: string; paymasterToken?: string };\n /**\n * Forward the caller's Privy access token (the request's `Authorization: Bearer`) to the paymaster as ERC-7677\n * `context.privyAccessToken`. The v2 FREE TIER requires it; a project paying from its own deposit does not.\n * Default `true`. Set `false` if your paymaster URL is not a PEPU policy service you trust with the token.\n */\n forwardPrivyToken?: boolean;\n /** Session length. Default env `SESSION_DURATION_MINUTES`, then 15; clamped to 1..1440. */\n minutes?: number;\n /** The one action users take with their session. */\n act: {\n /** Validate the client body. Throw to reject with 400. */\n parse(body: unknown): I;\n /** The calls to send. Each is re-checked against `scope` before sponsoring. */\n buildCalls(input: I, ctx: { kernelAddress: Address; ownerAddress: Address }): Call[];\n };\n /** Privy client for the default authentication. Default `createPrivyServer()`. */\n privy?: PrivyClient;\n /**\n * Custom authentication. Default: B1's `requireUser` (verifies the Privy\n * bearer token and reads the user's embedded wallet from Privy).\n */\n authenticate?: ComboAuthenticate;\n /** Chain reads. Default: viem on the PEPU RPC (`PEPU_RPC_URL` aware). */\n publicClient?: PublicClient;\n /**\n * A brand-new user's embedded wallet exists in the browser a moment before Privy's server reports it. With the\n * default authentication, a signed-in user whose wallet is not visible yet is looked up again this many times\n * (`attempts`, default 3), waiting `delayMs` * attempt number between lookups (default 400 ms). If it is still\n * not visible, `status` answers `{ active: false, provisioning: true }` (a normal state, not an error) and the other\n * routes answer a retryable 409 `WALLET_NOT_PROVISIONED`.\n */\n provisioningWait?: { attempts?: number; delayMs?: number };\n}\n\n/** The five route handlers returned by {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutes {\n prepare: { POST(request: Request): Promise<Response> };\n activate: { POST(request: Request): Promise<Response> };\n status: { GET(request: Request): Promise<Response> };\n act: { POST(request: Request): Promise<Response> };\n revoke: { POST(request: Request): Promise<Response> };\n}\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n}\n\n/** Anything unclassified that reaches a route is an upstream failure, not our 500. */\nfunction upstream(e: unknown, op: string): PepuError {\n const err = toPepuError(e, { op });\n if (err.code === \"UNKNOWN\" && !(e instanceof PepuError)) {\n return new PepuChainError(\"UNKNOWN\", err.message, { status: 502, cause: e });\n }\n return err;\n}\n\nasync function guard(op: string, fn: () => Promise<Response>): Promise<Response> {\n try {\n return await fn();\n } catch (e) {\n return toErrorResponse(upstream(e, op));\n }\n}\n\n/** The bearer token on a request, or `\"\"`. */\nfunction bearerToken(request: Request): string {\n return (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer\\s+/i, \"\").trim();\n}\n\n/** Marker: signed in, but Privy's server does not list an embedded wallet yet. */\nconst PROVISIONING = Symbol(\"wallet-provisioning\");\n\nconst nowSeconds = (): number => Math.floor(Date.now() / 1000);\n\nfunction defaultPublicClient(): PublicClient {\n return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) }) as PublicClient;\n}\n\n/**\n * Route handlers for the Kernel session lifecycle.\n *\n * - `prepare.POST`: the server creates a fresh session key and decides the\n * expiry. The private key stays on the server; the response carries only the\n * key's address, the expiry and the scope, so the browser can ask the owner\n * for the ONE signature that grants exactly that. Calling it again replaces\n * any pending or active session (the old key is dropped).\n * - `activate.POST` `{ approval }`: checks the approval is for this user's\n * smart account and for exactly the key, scope and expiry issued in\n * `prepare`, then stores it. 409 `SESSION_NONE` when nothing is pending,\n * 410 `SESSION_EXPIRED` for an expired offer, 400 `SESSION_APPROVAL_MISMATCH`.\n * - `status.GET`: `{ active: false }` or `{ active: true, validUntil, ... }`.\n * Never returns the session key or approval.\n * - `act.POST`: signs ONE sponsored UserOperation with the session key. 409\n * `SESSION_NONE` without a live session, 429 while another action runs.\n * - `revoke.POST`: deletes the session key and approval from the server, so\n * the app can no longer act, immediately. It does NOT uninstall the\n * permission on-chain: that grant stays valid until its expiry, but only the\n * deleted key can use it and only within the scope. An on-chain uninstall is\n * an owner-signed call to the user's own account, which a paymaster\n * destination allowlist rightly does not sponsor.\n *\n * Gas: the paymaster policy service reserves worst-case cost per operation:\n * about 20.5 PEPU for a session's first operation and about 6.9 PEPU for later\n * ones (`SESSION_GAS_RESERVATION_PEPU`). Size spend caps above that. Fees come\n * from the chain with 20% headroom.\n *\n * @example\n * // lib/session-routes.ts\n * export const routes = createSponsoredSessionRoutes({\n * scope: { calls: [{ target: tapScore, abi: tapScoreAbi, functionName: \"tap\" }] },\n * store: createMemoryStore(), // DEV ONLY\n * act: {\n * parse: () => ({}),\n * buildCalls: () => [{ to: tapScore, abi: tapScoreAbi, functionName: \"tap\" }],\n * },\n * });\n * // app/api/session/prepare/route.ts: export const { POST } = routes.prepare;\n */\nexport function createSponsoredSessionRoutes<I>(o: SponsoredSessionRoutesOptions<I>): SponsoredSessionRoutes {\n // A call whose target is empty or undefined (an unset env variable) is \"not configured yet\":\n // every route then answers CONFIG_MISSING_ENV at request time. A malformed non-empty scope\n // still fails at startup, not on the first request.\n const unconfigured = o.scope.calls.some((c) => !c.target || String(c.target).trim() === \"\");\n if (unconfigured) {\n const unset = async (): Promise<Response> =>\n toErrorResponse(\n new PepuConfigError(\n \"CONFIG_MISSING_ENV\",\n `${o.scope.targetEnv ?? \"A session target contract address\"} is not set to a valid address. See .env.example.`,\n { hint: \"Set it and restart the server.\" },\n ),\n );\n return {\n prepare: { POST: unset },\n activate: { POST: unset },\n status: { GET: unset },\n act: { POST: unset },\n revoke: { POST: unset },\n };\n }\n buildKernelSessionPolicies({ calls: o.scope.calls, validUntil: 1 });\n let publicClient = o.publicClient;\n const client = (): PublicClient => (publicClient ??= defaultPublicClient());\n\n const wait = { attempts: o.provisioningWait?.attempts ?? 3, delayMs: o.provisioningWait?.delayMs ?? 400 };\n\n /**\n * Authenticate. A signed-in user whose wallet Privy's server does not list yet is looked up again (bounded), then\n * reported as `PROVISIONING` so the caller decides: `status` makes it a normal state, the rest throw a retryable 409.\n */\n const authenticateOrProvisioning = async (request: Request): Promise<ComboUser | Response | typeof PROVISIONING> => {\n if (o.authenticate) {\n const user = await o.authenticate(request);\n if (!user) throw new PepuAuthError(\"AUTH_INVALID_TOKEN\", \"Missing or invalid Privy access token.\");\n return user;\n }\n const privy = o.privy ?? createPrivyServer();\n for (let attempt = 0; ; attempt++) {\n const auth = await requireUser(request, { privy });\n if (!auth.ok) return auth.response;\n if (auth.user.address) return { userId: auth.user.userId, ownerAddress: auth.user.address };\n if (attempt >= wait.attempts) return PROVISIONING;\n await new Promise((resolve) => setTimeout(resolve, wait.delayMs * (attempt + 1)));\n }\n };\n\n const authenticate = async (request: Request): Promise<ComboUser | Response> => {\n const user = await authenticateOrProvisioning(request);\n if (user === PROVISIONING) {\n throw new PepuAuthError(\n \"WALLET_NOT_PROVISIONED\",\n \"Your wallet is still being set up. This usually takes a few seconds; retrying.\",\n { status: 409, retryable: true },\n );\n }\n return user;\n };\n\n const minutes = (): number => o.minutes ?? resolveSessionMinutes(process.env.SESSION_DURATION_MINUTES);\n const policiesFor = (validUntil: number) => buildKernelSessionPolicies({ calls: o.scope.calls, validUntil });\n\n return {\n prepare: {\n POST: (request) =>\n guard(\"combo prepare\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const { userId, ownerAddress } = user;\n const mins = minutes();\n const validUntil = sessionExpiry(nowSeconds(), mins);\n const key = generateSessionKey();\n const policies = policiesFor(validUntil);\n const [kernelAddress, permissionId] = await Promise.all([\n getKernelAddress(client(), ownerAddress),\n expectedPermissionId({ publicClient: client(), sessionKeyAddress: key.address, policies }),\n ]);\n const record: SessionRecord = {\n userId,\n ownerAddress,\n kernelAddress,\n sessionPrivateKey: key.privateKey,\n sessionKeyAddress: key.address,\n permissionId,\n validUntil,\n approval: null,\n actions: 0,\n };\n await o.store.set(record);\n return json({\n ownerAddress,\n kernelAddress,\n sessionKeyAddress: key.address,\n validUntil,\n minutes: mins,\n scope: describeKernelSessionScope({ calls: o.scope.calls, validUntil }),\n });\n }),\n },\n\n activate: {\n POST: (request) =>\n guard(\"combo activate\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const body = (await request.json().catch(() => null)) as { approval?: unknown } | null;\n if (typeof body?.approval !== \"string\") {\n throw new PepuPolicyError(\"UNKNOWN\", \"Missing approval.\", { status: 400, hint: \"Send { approval }.\" });\n }\n const record = await o.store.get(user.userId);\n if (!record || record.approval !== null) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No pending session. Start again.\");\n }\n if (nowSeconds() >= record.validUntil) {\n await o.store.delete(record.userId);\n throw new PepuSessionError(\"SESSION_EXPIRED\", \"The session offer expired. Start again.\");\n }\n const check = checkApproval(body.approval, {\n kernelAddress: record.kernelAddress,\n permissionId: record.permissionId,\n });\n if (!check.ok) throw new PepuSessionError(\"SESSION_APPROVAL_MISMATCH\", check.reason, { status: 400 });\n await o.store.set({ ...record, approval: body.approval });\n return json({ active: true, validUntil: record.validUntil });\n }),\n },\n\n status: {\n GET: (request) =>\n guard(\"combo status\", async () => {\n const user = await authenticateOrProvisioning(request);\n if (user instanceof Response) return user;\n if (user === PROVISIONING) return json({ active: false, provisioning: true });\n const record = await o.store.get(user.userId);\n if (!record || !isLive(record, nowSeconds())) return json({ active: false });\n return json({\n active: true,\n validUntil: record.validUntil,\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n sessionKeyAddress: record.sessionKeyAddress,\n actions: record.actions,\n });\n }),\n },\n\n act: {\n POST: (request) =>\n guard(\"combo act\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const record = await o.store.get(user.userId);\n if (!record || !record.approval || !isLive(record, nowSeconds())) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No active session. Start one first.\");\n }\n\n let input: I;\n try {\n input = o.act.parse(await request.json().catch(() => ({})));\n } catch (e) {\n throw new PepuPolicyError(\"UNKNOWN\", e instanceof Error ? e.message : \"Invalid request body.\", {\n status: 400,\n hint: \"Fix the request body.\",\n cause: e,\n });\n }\n const calls = o.act.buildCalls(input, {\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n });\n // Fail fast; the chain is the real enforcement (see the file comment).\n assertCallsInScope(describeKernelSessionScope({ calls: o.scope.calls, validUntil: record.validUntil }), calls);\n\n if (!(await o.store.tryLock(user.userId))) {\n throw new PepuChainError(\"UNKNOWN\", \"An action is already in flight.\", {\n status: 429,\n retryable: true,\n hint: \"Wait for the current action to finish.\",\n });\n }\n const privyToken = o.forwardPrivyToken === false ? \"\" : bearerToken(request);\n try {\n const account = await loadKernelSessionAccount({\n publicClient: client(),\n approval: record.approval,\n sessionPrivateKey: record.sessionPrivateKey,\n });\n const kernel = createPepuSponsoredClient({\n account,\n publicClient: client(),\n ...(o.endpoints?.bundlerUrl !== undefined ? { bundlerUrl: o.endpoints.bundlerUrl } : {}),\n ...(o.endpoints?.paymasterUrl !== undefined ? { paymasterUrl: o.endpoints.paymasterUrl } : {}),\n ...(o.endpoints?.paymasterToken !== undefined ? { paymasterToken: o.endpoints.paymasterToken } : {}),\n ...(privyToken ? { paymasterContext: buildPaymasterContext({ privyAccessToken: privyToken }) } : {}),\n });\n const result = await sendSponsored({ client: kernel, calls });\n const actions = record.actions + (result.success ? 1 : 0);\n if (result.success) await o.store.set({ ...record, actions });\n const out: SponsoredActResult = {\n userOpHash: result.userOpHash,\n transactionHash: result.transactionHash,\n kernelAddress: record.kernelAddress,\n success: result.success,\n paymaster: result.paymaster,\n actualGasCostWei: result.actualGasCostWei.toString(),\n explorerUrl: result.explorerUrl,\n actions,\n };\n return json(out);\n } finally {\n await o.store.unlock(user.userId);\n }\n }),\n },\n\n revoke: {\n POST: (request) =>\n guard(\"combo revoke\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n await o.store.delete(user.userId);\n return json({ active: false });\n }),\n },\n };\n}\n\n/**\n * Throws `POLICY_UNSCOPED` (403) unless every call targets an allowed contract\n * and function selector with a value within the limit. Pure; used by the act\n * route and exported for custom routes.\n *\n * @example\n * assertCallsInScope(describeKernelSessionScope({ calls, validUntil }), [{ to, abi, functionName: \"tap\" }]);\n */\nexport function assertCallsInScope(scope: Pick<KernelSessionScope, \"calls\">, calls: readonly Call[]): void {\n for (const c of normalizeCalls(calls)) {\n if (!isCallInScope(scope, c)) {\n throw new PepuPolicyError(\"POLICY_UNSCOPED\", \"A call is outside the session scope.\", {\n status: 403,\n hint: \"Only the contracts and functions the user approved can be called.\",\n });\n }\n }\n}\n"]}
|
package/dist/combo.d.cts
CHANGED
|
@@ -66,6 +66,17 @@ interface SponsoredSessionRoutesOptions<I> {
|
|
|
66
66
|
authenticate?: ComboAuthenticate;
|
|
67
67
|
/** Chain reads. Default: viem on the PEPU RPC (`PEPU_RPC_URL` aware). */
|
|
68
68
|
publicClient?: PublicClient;
|
|
69
|
+
/**
|
|
70
|
+
* A brand-new user's embedded wallet exists in the browser a moment before Privy's server reports it. With the
|
|
71
|
+
* default authentication, a signed-in user whose wallet is not visible yet is looked up again this many times
|
|
72
|
+
* (`attempts`, default 3), waiting `delayMs` * attempt number between lookups (default 400 ms). If it is still
|
|
73
|
+
* not visible, `status` answers `{ active: false, provisioning: true }` (a normal state, not an error) and the other
|
|
74
|
+
* routes answer a retryable 409 `WALLET_NOT_PROVISIONED`.
|
|
75
|
+
*/
|
|
76
|
+
provisioningWait?: {
|
|
77
|
+
attempts?: number;
|
|
78
|
+
delayMs?: number;
|
|
79
|
+
};
|
|
69
80
|
}
|
|
70
81
|
/** The five route handlers returned by {@link createSponsoredSessionRoutes}. */
|
|
71
82
|
interface SponsoredSessionRoutes {
|
package/dist/combo.d.ts
CHANGED
|
@@ -66,6 +66,17 @@ interface SponsoredSessionRoutesOptions<I> {
|
|
|
66
66
|
authenticate?: ComboAuthenticate;
|
|
67
67
|
/** Chain reads. Default: viem on the PEPU RPC (`PEPU_RPC_URL` aware). */
|
|
68
68
|
publicClient?: PublicClient;
|
|
69
|
+
/**
|
|
70
|
+
* A brand-new user's embedded wallet exists in the browser a moment before Privy's server reports it. With the
|
|
71
|
+
* default authentication, a signed-in user whose wallet is not visible yet is looked up again this many times
|
|
72
|
+
* (`attempts`, default 3), waiting `delayMs` * attempt number between lookups (default 400 ms). If it is still
|
|
73
|
+
* not visible, `status` answers `{ active: false, provisioning: true }` (a normal state, not an error) and the other
|
|
74
|
+
* routes answer a retryable 409 `WALLET_NOT_PROVISIONED`.
|
|
75
|
+
*/
|
|
76
|
+
provisioningWait?: {
|
|
77
|
+
attempts?: number;
|
|
78
|
+
delayMs?: number;
|
|
79
|
+
};
|
|
69
80
|
}
|
|
70
81
|
/** The five route handlers returned by {@link createSponsoredSessionRoutes}. */
|
|
71
82
|
interface SponsoredSessionRoutes {
|
package/dist/combo.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import { buildKernelSessionPolicies, isLive, loadKernelSessionAccount, generateSessionKey, expectedPermissionId } from './chunk-
|
|
2
|
-
export { createMemoryStore, isLive } from './chunk-
|
|
3
|
-
import { createPepuSponsoredClient, sendSponsored, getKernelAddress } from './chunk-
|
|
4
|
-
import './chunk-
|
|
1
|
+
import { buildKernelSessionPolicies, isLive, loadKernelSessionAccount, generateSessionKey, expectedPermissionId } from './chunk-NHPWXIA2.js';
|
|
2
|
+
export { createMemoryStore, isLive } from './chunk-NHPWXIA2.js';
|
|
3
|
+
import { createPepuSponsoredClient, sendSponsored, getKernelAddress } from './chunk-QIDMFFAQ.js';
|
|
4
|
+
import './chunk-QZKUPCUD.js';
|
|
5
5
|
import { normalizeCalls } from './chunk-VBH3JLQ5.js';
|
|
6
|
-
import './chunk-
|
|
6
|
+
import './chunk-RSPAN44L.js';
|
|
7
7
|
import { buildPaymasterContext } from './chunk-7PVR7QSE.js';
|
|
8
|
-
import './chunk-
|
|
8
|
+
import './chunk-GFKIM7HT.js';
|
|
9
9
|
import './chunk-KJYNF5KH.js';
|
|
10
|
+
import './chunk-GIZNH65Q.js';
|
|
10
11
|
import { isCallInScope, describeKernelSessionScope, checkApproval } from './chunk-ESMNAXUI.js';
|
|
11
12
|
import './chunk-J6UXXHBE.js';
|
|
12
13
|
import { resolvePepuEndpoints } from './chunk-XC4IBCI2.js';
|
|
13
14
|
import { pepuMainnet } from './chunk-VTQIHMF3.js';
|
|
14
|
-
import {
|
|
15
|
+
import { createPrivyServer, requireUser } from './chunk-62M2LKQW.js';
|
|
15
16
|
import { assertServerOnly } from './chunk-W3JN3YIW.js';
|
|
16
17
|
import './chunk-3XUGQODR.js';
|
|
17
18
|
import { sessionExpiry, resolveSessionMinutes } from './chunk-YKEWWQEJ.js';
|
|
@@ -40,6 +41,7 @@ async function guard(op, fn) {
|
|
|
40
41
|
function bearerToken(request) {
|
|
41
42
|
return (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
|
|
42
43
|
}
|
|
44
|
+
var PROVISIONING = /* @__PURE__ */ Symbol("wallet-provisioning");
|
|
43
45
|
var nowSeconds = () => Math.floor(Date.now() / 1e3);
|
|
44
46
|
function defaultPublicClient() {
|
|
45
47
|
return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) });
|
|
@@ -65,20 +67,32 @@ function createSponsoredSessionRoutes(o) {
|
|
|
65
67
|
buildKernelSessionPolicies({ calls: o.scope.calls, validUntil: 1 });
|
|
66
68
|
let publicClient = o.publicClient;
|
|
67
69
|
const client = () => publicClient ??= defaultPublicClient();
|
|
68
|
-
const
|
|
70
|
+
const wait = { attempts: o.provisioningWait?.attempts ?? 3, delayMs: o.provisioningWait?.delayMs ?? 400 };
|
|
71
|
+
const authenticateOrProvisioning = async (request) => {
|
|
69
72
|
if (o.authenticate) {
|
|
70
73
|
const user = await o.authenticate(request);
|
|
71
74
|
if (!user) throw new PepuAuthError("AUTH_INVALID_TOKEN", "Missing or invalid Privy access token.");
|
|
72
75
|
return user;
|
|
73
76
|
}
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
77
|
+
const privy = o.privy ?? createPrivyServer();
|
|
78
|
+
for (let attempt = 0; ; attempt++) {
|
|
79
|
+
const auth = await requireUser(request, { privy });
|
|
80
|
+
if (!auth.ok) return auth.response;
|
|
81
|
+
if (auth.user.address) return { userId: auth.user.userId, ownerAddress: auth.user.address };
|
|
82
|
+
if (attempt >= wait.attempts) return PROVISIONING;
|
|
83
|
+
await new Promise((resolve) => setTimeout(resolve, wait.delayMs * (attempt + 1)));
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const authenticate = async (request) => {
|
|
87
|
+
const user = await authenticateOrProvisioning(request);
|
|
88
|
+
if (user === PROVISIONING) {
|
|
89
|
+
throw new PepuAuthError(
|
|
90
|
+
"WALLET_NOT_PROVISIONED",
|
|
91
|
+
"Your wallet is still being set up. This usually takes a few seconds; retrying.",
|
|
92
|
+
{ status: 409, retryable: true }
|
|
93
|
+
);
|
|
80
94
|
}
|
|
81
|
-
return
|
|
95
|
+
return user;
|
|
82
96
|
};
|
|
83
97
|
const minutes = () => o.minutes ?? resolveSessionMinutes(process.env.SESSION_DURATION_MINUTES);
|
|
84
98
|
const policiesFor = (validUntil) => buildKernelSessionPolicies({ calls: o.scope.calls, validUntil });
|
|
@@ -145,8 +159,9 @@ function createSponsoredSessionRoutes(o) {
|
|
|
145
159
|
},
|
|
146
160
|
status: {
|
|
147
161
|
GET: (request) => guard("combo status", async () => {
|
|
148
|
-
const user = await
|
|
162
|
+
const user = await authenticateOrProvisioning(request);
|
|
149
163
|
if (user instanceof Response) return user;
|
|
164
|
+
if (user === PROVISIONING) return json({ active: false, provisioning: true });
|
|
150
165
|
const record = await o.store.get(user.userId);
|
|
151
166
|
if (!record || !isLive(record, nowSeconds())) return json({ active: false });
|
|
152
167
|
return json({
|
package/dist/combo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/combo/server.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCA,gBAAA,CAAiB,uBAAuB,CAAA;AA0FxC,SAAS,IAAA,CAAK,IAAA,EAAe,MAAA,GAAS,GAAA,EAAe;AACnD,EAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA,EAAG,EAAE,MAAA,EAAQ,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,IAAsB,CAAA;AACvG;AAGA,SAAS,QAAA,CAAS,GAAY,EAAA,EAAuB;AACnD,EAAA,MAAM,GAAA,GAAM,WAAA,CAAY,CAAA,EAAG,EAAE,IAAI,CAAA;AACjC,EAAA,IAAI,GAAA,CAAI,IAAA,KAAS,SAAA,IAAa,EAAE,aAAa,SAAA,CAAA,EAAY;AACvD,IAAA,OAAO,IAAI,cAAA,CAAe,SAAA,EAAW,GAAA,CAAI,OAAA,EAAS,EAAE,MAAA,EAAQ,GAAA,EAAK,KAAA,EAAO,CAAA,EAAG,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,GAAA;AACT;AAEA,eAAe,KAAA,CAAM,IAAY,EAAA,EAAgD;AAC/E,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,EAAA,EAAG;AAAA,EAClB,SAAS,CAAA,EAAG;AACV,IAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,EACxC;AACF;AAG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AAA,EACF;AACF","file":"combo.js","sourcesContent":["import type { PrivyClient } from \"@privy-io/node\";\nimport { createPublicClient, http } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\nimport type { SponsoredActResult } from \"./types.js\";\nimport { createPepuSponsoredClient, sendSponsored } from \"../aa/kernel.js\";\nimport { normalizeCalls } from \"../aa/calls.js\";\nimport type { Call } from \"../aa/types.js\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { resolvePepuEndpoints } from \"../endpoints.js\";\nimport { buildPaymasterContext } from \"../erc7677.js\";\nimport {\n PepuAuthError,\n PepuChainError,\n PepuConfigError,\n PepuError,\n PepuPolicyError,\n PepuSessionError,\n toErrorResponse,\n toPepuError,\n} from \"../errors.js\";\nimport { assertServerOnly } from \"../internal/assert-server.js\";\nimport { createPrivyServer, requireUser } from \"../privy/server.js\";\nimport { resolveSessionMinutes, sessionExpiry } from \"../session/policy.js\";\nimport {\n buildKernelSessionPolicies,\n checkApproval,\n describeKernelSessionScope,\n expectedPermissionId,\n generateSessionKey,\n getKernelAddress,\n isCallInScope,\n loadKernelSessionAccount,\n} from \"../session/kernel.js\";\nimport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nimport { isLive } from \"../session/store.js\";\nimport type { SessionRecord, SessionStore } from \"../session/store.js\";\n\nassertServerOnly(\"@pepu-chain/sdk/combo\");\n\n/**\n * `@pepu-chain/sdk/combo` (server): the combined flow. Google sign-in (Privy),\n * a ONE-TIME on-chain session, and sponsored gas. Route factories for the\n * Kernel session lifecycle: prepare, activate, status, act, revoke.\n *\n * Extracted from templates/sponsored-session-app/app/api/session/* and\n * lib/{kernel,session-auth}.ts.\n *\n * Trust model: the chain, not these routes, enforces scope. The owner's single\n * EIP-712 signature enables a permission whose call policy (targets,\n * selectors, zero value) and timestamp policy the Kernel account verifies on\n * every UserOperation. The checks here only fail fast.\n *\n * Optional peers: `@privy-io/node`, `@zerodev/*`.\n */\n\nexport { createMemoryStore, isLive } from \"../session/store.js\";\nexport type { SessionRecord, SessionStore } from \"../session/store.js\";\nexport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nexport type { SponsoredActResult } from \"./types.js\";\n/** Session length from `SESSION_DURATION_MINUTES` (default 15, clamped to 1..1440), the same rule the routes use. */\nexport { resolveSessionMinutes } from \"../session/policy.js\";\n\n/** The authenticated caller of a combo route. */\nexport interface ComboUser {\n userId: string;\n /** The user's Privy embedded wallet: the owner of their Kernel account. From Privy, never the request. */\n ownerAddress: Address;\n}\n\n/** Authenticate a request. Throw a `PepuError` (or return `null`) when it is not valid. */\nexport type ComboAuthenticate = (request: Request) => Promise<ComboUser | null>;\n\n/** Options for {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutesOptions<I> {\n /** What the session may call. Enforced on-chain by the call policy. */\n scope: {\n calls: readonly KernelSessionCall[];\n /** Env variable named in the `CONFIG_MISSING_ENV` message when a call target is empty (unset). */\n targetEnv?: string;\n };\n /**\n * Where session records (including the session private key) live. Use\n * `createMemoryStore()` for development only: production needs a persistent\n * store with the key encrypted at rest.\n */\n store: SessionStore;\n /**\n * Bundler and paymaster. The bundler defaults to env `PEPU_BUNDLER_URL`, then the hosted bundler. The paymaster\n * needs a complete ERC-7677 URL (env `PEPU_PAYMASTER_URL`, or `paymasterUrl`) or a project `paymasterToken`\n * (built against the hosted paymaster base).\n */\n endpoints?: { bundlerUrl?: string; paymasterUrl?: string; paymasterToken?: string };\n /**\n * Forward the caller's Privy access token (the request's `Authorization: Bearer`) to the paymaster as ERC-7677\n * `context.privyAccessToken`. The v2 FREE TIER requires it; a project paying from its own deposit does not.\n * Default `true`. Set `false` if your paymaster URL is not a PEPU policy service you trust with the token.\n */\n forwardPrivyToken?: boolean;\n /** Session length. Default env `SESSION_DURATION_MINUTES`, then 15; clamped to 1..1440. */\n minutes?: number;\n /** The one action users take with their session. */\n act: {\n /** Validate the client body. Throw to reject with 400. */\n parse(body: unknown): I;\n /** The calls to send. Each is re-checked against `scope` before sponsoring. */\n buildCalls(input: I, ctx: { kernelAddress: Address; ownerAddress: Address }): Call[];\n };\n /** Privy client for the default authentication. Default `createPrivyServer()`. */\n privy?: PrivyClient;\n /**\n * Custom authentication. Default: B1's `requireUser` (verifies the Privy\n * bearer token and reads the user's embedded wallet from Privy).\n */\n authenticate?: ComboAuthenticate;\n /** Chain reads. Default: viem on the PEPU RPC (`PEPU_RPC_URL` aware). */\n publicClient?: PublicClient;\n}\n\n/** The five route handlers returned by {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutes {\n prepare: { POST(request: Request): Promise<Response> };\n activate: { POST(request: Request): Promise<Response> };\n status: { GET(request: Request): Promise<Response> };\n act: { POST(request: Request): Promise<Response> };\n revoke: { POST(request: Request): Promise<Response> };\n}\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n}\n\n/** Anything unclassified that reaches a route is an upstream failure, not our 500. */\nfunction upstream(e: unknown, op: string): PepuError {\n const err = toPepuError(e, { op });\n if (err.code === \"UNKNOWN\" && !(e instanceof PepuError)) {\n return new PepuChainError(\"UNKNOWN\", err.message, { status: 502, cause: e });\n }\n return err;\n}\n\nasync function guard(op: string, fn: () => Promise<Response>): Promise<Response> {\n try {\n return await fn();\n } catch (e) {\n return toErrorResponse(upstream(e, op));\n }\n}\n\n/** The bearer token on a request, or `\"\"`. */\nfunction bearerToken(request: Request): string {\n return (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer\\s+/i, \"\").trim();\n}\n\nconst nowSeconds = (): number => Math.floor(Date.now() / 1000);\n\nfunction defaultPublicClient(): PublicClient {\n return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) }) as PublicClient;\n}\n\n/**\n * Route handlers for the Kernel session lifecycle.\n *\n * - `prepare.POST`: the server creates a fresh session key and decides the\n * expiry. The private key stays on the server; the response carries only the\n * key's address, the expiry and the scope, so the browser can ask the owner\n * for the ONE signature that grants exactly that. Calling it again replaces\n * any pending or active session (the old key is dropped).\n * - `activate.POST` `{ approval }`: checks the approval is for this user's\n * smart account and for exactly the key, scope and expiry issued in\n * `prepare`, then stores it. 409 `SESSION_NONE` when nothing is pending,\n * 410 `SESSION_EXPIRED` for an expired offer, 400 `SESSION_APPROVAL_MISMATCH`.\n * - `status.GET`: `{ active: false }` or `{ active: true, validUntil, ... }`.\n * Never returns the session key or approval.\n * - `act.POST`: signs ONE sponsored UserOperation with the session key. 409\n * `SESSION_NONE` without a live session, 429 while another action runs.\n * - `revoke.POST`: deletes the session key and approval from the server, so\n * the app can no longer act, immediately. It does NOT uninstall the\n * permission on-chain: that grant stays valid until its expiry, but only the\n * deleted key can use it and only within the scope. An on-chain uninstall is\n * an owner-signed call to the user's own account, which a paymaster\n * destination allowlist rightly does not sponsor.\n *\n * Gas: the paymaster policy service reserves worst-case cost per operation:\n * about 20.5 PEPU for a session's first operation and about 6.9 PEPU for later\n * ones (`SESSION_GAS_RESERVATION_PEPU`). Size spend caps above that. Fees come\n * from the chain with 20% headroom.\n *\n * @example\n * // lib/session-routes.ts\n * export const routes = createSponsoredSessionRoutes({\n * scope: { calls: [{ target: tapScore, abi: tapScoreAbi, functionName: \"tap\" }] },\n * store: createMemoryStore(), // DEV ONLY\n * act: {\n * parse: () => ({}),\n * buildCalls: () => [{ to: tapScore, abi: tapScoreAbi, functionName: \"tap\" }],\n * },\n * });\n * // app/api/session/prepare/route.ts: export const { POST } = routes.prepare;\n */\nexport function createSponsoredSessionRoutes<I>(o: SponsoredSessionRoutesOptions<I>): SponsoredSessionRoutes {\n // A call whose target is empty or undefined (an unset env variable) is \"not configured yet\":\n // every route then answers CONFIG_MISSING_ENV at request time. A malformed non-empty scope\n // still fails at startup, not on the first request.\n const unconfigured = o.scope.calls.some((c) => !c.target || String(c.target).trim() === \"\");\n if (unconfigured) {\n const unset = async (): Promise<Response> =>\n toErrorResponse(\n new PepuConfigError(\n \"CONFIG_MISSING_ENV\",\n `${o.scope.targetEnv ?? \"A session target contract address\"} is not set to a valid address. See .env.example.`,\n { hint: \"Set it and restart the server.\" },\n ),\n );\n return {\n prepare: { POST: unset },\n activate: { POST: unset },\n status: { GET: unset },\n act: { POST: unset },\n revoke: { POST: unset },\n };\n }\n buildKernelSessionPolicies({ calls: o.scope.calls, validUntil: 1 });\n let publicClient = o.publicClient;\n const client = (): PublicClient => (publicClient ??= defaultPublicClient());\n\n const authenticate = async (request: Request): Promise<ComboUser | Response> => {\n if (o.authenticate) {\n const user = await o.authenticate(request);\n if (!user) throw new PepuAuthError(\"AUTH_INVALID_TOKEN\", \"Missing or invalid Privy access token.\");\n return user;\n }\n const auth = await requireUser(request, { privy: o.privy ?? createPrivyServer() });\n if (!auth.ok) return auth.response;\n if (!auth.user.address) {\n throw new PepuAuthError(\"WALLET_NOT_PROVISIONED\", \"No embedded wallet yet. Create it first (ensure-wallet route).\", {\n status: 409,\n });\n }\n return { userId: auth.user.userId, ownerAddress: auth.user.address };\n };\n\n const minutes = (): number => o.minutes ?? resolveSessionMinutes(process.env.SESSION_DURATION_MINUTES);\n const policiesFor = (validUntil: number) => buildKernelSessionPolicies({ calls: o.scope.calls, validUntil });\n\n return {\n prepare: {\n POST: (request) =>\n guard(\"combo prepare\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const { userId, ownerAddress } = user;\n const mins = minutes();\n const validUntil = sessionExpiry(nowSeconds(), mins);\n const key = generateSessionKey();\n const policies = policiesFor(validUntil);\n const [kernelAddress, permissionId] = await Promise.all([\n getKernelAddress(client(), ownerAddress),\n expectedPermissionId({ publicClient: client(), sessionKeyAddress: key.address, policies }),\n ]);\n const record: SessionRecord = {\n userId,\n ownerAddress,\n kernelAddress,\n sessionPrivateKey: key.privateKey,\n sessionKeyAddress: key.address,\n permissionId,\n validUntil,\n approval: null,\n actions: 0,\n };\n await o.store.set(record);\n return json({\n ownerAddress,\n kernelAddress,\n sessionKeyAddress: key.address,\n validUntil,\n minutes: mins,\n scope: describeKernelSessionScope({ calls: o.scope.calls, validUntil }),\n });\n }),\n },\n\n activate: {\n POST: (request) =>\n guard(\"combo activate\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const body = (await request.json().catch(() => null)) as { approval?: unknown } | null;\n if (typeof body?.approval !== \"string\") {\n throw new PepuPolicyError(\"UNKNOWN\", \"Missing approval.\", { status: 400, hint: \"Send { approval }.\" });\n }\n const record = await o.store.get(user.userId);\n if (!record || record.approval !== null) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No pending session. Start again.\");\n }\n if (nowSeconds() >= record.validUntil) {\n await o.store.delete(record.userId);\n throw new PepuSessionError(\"SESSION_EXPIRED\", \"The session offer expired. Start again.\");\n }\n const check = checkApproval(body.approval, {\n kernelAddress: record.kernelAddress,\n permissionId: record.permissionId,\n });\n if (!check.ok) throw new PepuSessionError(\"SESSION_APPROVAL_MISMATCH\", check.reason, { status: 400 });\n await o.store.set({ ...record, approval: body.approval });\n return json({ active: true, validUntil: record.validUntil });\n }),\n },\n\n status: {\n GET: (request) =>\n guard(\"combo status\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const record = await o.store.get(user.userId);\n if (!record || !isLive(record, nowSeconds())) return json({ active: false });\n return json({\n active: true,\n validUntil: record.validUntil,\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n sessionKeyAddress: record.sessionKeyAddress,\n actions: record.actions,\n });\n }),\n },\n\n act: {\n POST: (request) =>\n guard(\"combo act\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const record = await o.store.get(user.userId);\n if (!record || !record.approval || !isLive(record, nowSeconds())) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No active session. Start one first.\");\n }\n\n let input: I;\n try {\n input = o.act.parse(await request.json().catch(() => ({})));\n } catch (e) {\n throw new PepuPolicyError(\"UNKNOWN\", e instanceof Error ? e.message : \"Invalid request body.\", {\n status: 400,\n hint: \"Fix the request body.\",\n cause: e,\n });\n }\n const calls = o.act.buildCalls(input, {\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n });\n // Fail fast; the chain is the real enforcement (see the file comment).\n assertCallsInScope(describeKernelSessionScope({ calls: o.scope.calls, validUntil: record.validUntil }), calls);\n\n if (!(await o.store.tryLock(user.userId))) {\n throw new PepuChainError(\"UNKNOWN\", \"An action is already in flight.\", {\n status: 429,\n retryable: true,\n hint: \"Wait for the current action to finish.\",\n });\n }\n const privyToken = o.forwardPrivyToken === false ? \"\" : bearerToken(request);\n try {\n const account = await loadKernelSessionAccount({\n publicClient: client(),\n approval: record.approval,\n sessionPrivateKey: record.sessionPrivateKey,\n });\n const kernel = createPepuSponsoredClient({\n account,\n publicClient: client(),\n ...(o.endpoints?.bundlerUrl !== undefined ? { bundlerUrl: o.endpoints.bundlerUrl } : {}),\n ...(o.endpoints?.paymasterUrl !== undefined ? { paymasterUrl: o.endpoints.paymasterUrl } : {}),\n ...(o.endpoints?.paymasterToken !== undefined ? { paymasterToken: o.endpoints.paymasterToken } : {}),\n ...(privyToken ? { paymasterContext: buildPaymasterContext({ privyAccessToken: privyToken }) } : {}),\n });\n const result = await sendSponsored({ client: kernel, calls });\n const actions = record.actions + (result.success ? 1 : 0);\n if (result.success) await o.store.set({ ...record, actions });\n const out: SponsoredActResult = {\n userOpHash: result.userOpHash,\n transactionHash: result.transactionHash,\n kernelAddress: record.kernelAddress,\n success: result.success,\n paymaster: result.paymaster,\n actualGasCostWei: result.actualGasCostWei.toString(),\n explorerUrl: result.explorerUrl,\n actions,\n };\n return json(out);\n } finally {\n await o.store.unlock(user.userId);\n }\n }),\n },\n\n revoke: {\n POST: (request) =>\n guard(\"combo revoke\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n await o.store.delete(user.userId);\n return json({ active: false });\n }),\n },\n };\n}\n\n/**\n * Throws `POLICY_UNSCOPED` (403) unless every call targets an allowed contract\n * and function selector with a value within the limit. Pure; used by the act\n * route and exported for custom routes.\n *\n * @example\n * assertCallsInScope(describeKernelSessionScope({ calls, validUntil }), [{ to, abi, functionName: \"tap\" }]);\n */\nexport function assertCallsInScope(scope: Pick<KernelSessionScope, \"calls\">, calls: readonly Call[]): void {\n for (const c of normalizeCalls(calls)) {\n if (!isCallInScope(scope, c)) {\n throw new PepuPolicyError(\"POLICY_UNSCOPED\", \"A call is outside the session scope.\", {\n status: 403,\n hint: \"Only the contracts and functions the user approved can be called.\",\n });\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/combo/server.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqCA,gBAAA,CAAiB,uBAAuB,CAAA;AAkGxC,SAAS,IAAA,CAAK,IAAA,EAAe,MAAA,GAAS,GAAA,EAAe;AACnD,EAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA,EAAG,EAAE,MAAA,EAAQ,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,IAAsB,CAAA;AACvG;AAGA,SAAS,QAAA,CAAS,GAAY,EAAA,EAAuB;AACnD,EAAA,MAAM,GAAA,GAAM,WAAA,CAAY,CAAA,EAAG,EAAE,IAAI,CAAA;AACjC,EAAA,IAAI,GAAA,CAAI,IAAA,KAAS,SAAA,IAAa,EAAE,aAAa,SAAA,CAAA,EAAY;AACvD,IAAA,OAAO,IAAI,cAAA,CAAe,SAAA,EAAW,GAAA,CAAI,OAAA,EAAS,EAAE,MAAA,EAAQ,GAAA,EAAK,KAAA,EAAO,CAAA,EAAG,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,GAAA;AACT;AAEA,eAAe,KAAA,CAAM,IAAY,EAAA,EAAgD;AAC/E,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,EAAA,EAAG;AAAA,EAClB,SAAS,CAAA,EAAG;AACV,IAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,EACxC;AACF;AAGA,SAAS,YAAY,OAAA,EAA0B;AA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AAE,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAAA,QAClC;AAAA,MACF,CAAC;AAAA,KACL;AAAA,IAEA,MAAA,EAAQ;AAAA,MACN,IAAA,EAAM,CAAC,OAAA,KACL,KAAA,CAAM,gBAAgB,YAAY;AAChC,QAAA,MAAM,IAAA,GAAO,MAAM,YAAA,CAAa,OAAO,CAAA;AACvC,QAAA,IAAI,IAAA,YAAgB,UAAU,OAAO,IAAA;AACrC,QAAA,MAAM,CAAA,CAAE,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AAChC,QAAA,OAAO,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAA,EAAO,CAAA;AAAA,MAC/B,CAAC;AAAA;AACL,GACF;AACF;AAUO,SAAS,kBAAA,CAAmB,OAA0C,KAAA,EAA8B;AACzG,EAAA,KAAA,MAAW,CAAA,IAAK,cAAA,CAAe,KAAK,CAAA,EAAG;AACrC,IAAA,IAAI,CAAC,aAAA,CAAc,KAAA,EAAO,CAAC,CAAA,EAAG;AAC5B,MAAA,MAAM,IAAI,eAAA,CAAgB,iBAAA,EAAmB,sCAAA,EAAwC;AAAA,QACnF,MAAA,EAAQ,GAAA;AAAA,QACR,IAAA,EAAM;AAAA,OACP,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"combo.js","sourcesContent":["import type { PrivyClient } from \"@privy-io/node\";\nimport { createPublicClient, http } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\nimport type { SponsoredActResult } from \"./types.js\";\nimport { createPepuSponsoredClient, sendSponsored } from \"../aa/kernel.js\";\nimport { normalizeCalls } from \"../aa/calls.js\";\nimport type { Call } from \"../aa/types.js\";\nimport { pepuMainnet } from \"../chains.js\";\nimport { resolvePepuEndpoints } from \"../endpoints.js\";\nimport { buildPaymasterContext } from \"../erc7677.js\";\nimport {\n PepuAuthError,\n PepuChainError,\n PepuConfigError,\n PepuError,\n PepuPolicyError,\n PepuSessionError,\n toErrorResponse,\n toPepuError,\n} from \"../errors.js\";\nimport { assertServerOnly } from \"../internal/assert-server.js\";\nimport { createPrivyServer, requireUser } from \"../privy/server.js\";\nimport { resolveSessionMinutes, sessionExpiry } from \"../session/policy.js\";\nimport {\n buildKernelSessionPolicies,\n checkApproval,\n describeKernelSessionScope,\n expectedPermissionId,\n generateSessionKey,\n getKernelAddress,\n isCallInScope,\n loadKernelSessionAccount,\n} from \"../session/kernel.js\";\nimport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nimport { isLive } from \"../session/store.js\";\nimport type { SessionRecord, SessionStore } from \"../session/store.js\";\n\nassertServerOnly(\"@pepu-chain/sdk/combo\");\n\n/**\n * `@pepu-chain/sdk/combo` (server): the combined flow. Google sign-in (Privy),\n * a ONE-TIME on-chain session, and sponsored gas. Route factories for the\n * Kernel session lifecycle: prepare, activate, status, act, revoke.\n *\n * Extracted from templates/sponsored-session-app/app/api/session/* and\n * lib/{kernel,session-auth}.ts.\n *\n * Trust model: the chain, not these routes, enforces scope. The owner's single\n * EIP-712 signature enables a permission whose call policy (targets,\n * selectors, zero value) and timestamp policy the Kernel account verifies on\n * every UserOperation. The checks here only fail fast.\n *\n * Optional peers: `@privy-io/node`, `@zerodev/*`.\n */\n\nexport { createMemoryStore, isLive } from \"../session/store.js\";\nexport type { SessionRecord, SessionStore } from \"../session/store.js\";\nexport type { KernelSessionCall, KernelSessionScope } from \"../session/kernel.js\";\nexport type { SponsoredActResult } from \"./types.js\";\n/** Session length from `SESSION_DURATION_MINUTES` (default 15, clamped to 1..1440), the same rule the routes use. */\nexport { resolveSessionMinutes } from \"../session/policy.js\";\n\n/** The authenticated caller of a combo route. */\nexport interface ComboUser {\n userId: string;\n /** The user's Privy embedded wallet: the owner of their Kernel account. From Privy, never the request. */\n ownerAddress: Address;\n}\n\n/** Authenticate a request. Throw a `PepuError` (or return `null`) when it is not valid. */\nexport type ComboAuthenticate = (request: Request) => Promise<ComboUser | null>;\n\n/** Options for {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutesOptions<I> {\n /** What the session may call. Enforced on-chain by the call policy. */\n scope: {\n calls: readonly KernelSessionCall[];\n /** Env variable named in the `CONFIG_MISSING_ENV` message when a call target is empty (unset). */\n targetEnv?: string;\n };\n /**\n * Where session records (including the session private key) live. Use\n * `createMemoryStore()` for development only: production needs a persistent\n * store with the key encrypted at rest.\n */\n store: SessionStore;\n /**\n * Bundler and paymaster. The bundler defaults to env `PEPU_BUNDLER_URL`, then the hosted bundler. The paymaster\n * needs a complete ERC-7677 URL (env `PEPU_PAYMASTER_URL`, or `paymasterUrl`) or a project `paymasterToken`\n * (built against the hosted paymaster base).\n */\n endpoints?: { bundlerUrl?: string; paymasterUrl?: string; paymasterToken?: string };\n /**\n * Forward the caller's Privy access token (the request's `Authorization: Bearer`) to the paymaster as ERC-7677\n * `context.privyAccessToken`. The v2 FREE TIER requires it; a project paying from its own deposit does not.\n * Default `true`. Set `false` if your paymaster URL is not a PEPU policy service you trust with the token.\n */\n forwardPrivyToken?: boolean;\n /** Session length. Default env `SESSION_DURATION_MINUTES`, then 15; clamped to 1..1440. */\n minutes?: number;\n /** The one action users take with their session. */\n act: {\n /** Validate the client body. Throw to reject with 400. */\n parse(body: unknown): I;\n /** The calls to send. Each is re-checked against `scope` before sponsoring. */\n buildCalls(input: I, ctx: { kernelAddress: Address; ownerAddress: Address }): Call[];\n };\n /** Privy client for the default authentication. Default `createPrivyServer()`. */\n privy?: PrivyClient;\n /**\n * Custom authentication. Default: B1's `requireUser` (verifies the Privy\n * bearer token and reads the user's embedded wallet from Privy).\n */\n authenticate?: ComboAuthenticate;\n /** Chain reads. Default: viem on the PEPU RPC (`PEPU_RPC_URL` aware). */\n publicClient?: PublicClient;\n /**\n * A brand-new user's embedded wallet exists in the browser a moment before Privy's server reports it. With the\n * default authentication, a signed-in user whose wallet is not visible yet is looked up again this many times\n * (`attempts`, default 3), waiting `delayMs` * attempt number between lookups (default 400 ms). If it is still\n * not visible, `status` answers `{ active: false, provisioning: true }` (a normal state, not an error) and the other\n * routes answer a retryable 409 `WALLET_NOT_PROVISIONED`.\n */\n provisioningWait?: { attempts?: number; delayMs?: number };\n}\n\n/** The five route handlers returned by {@link createSponsoredSessionRoutes}. */\nexport interface SponsoredSessionRoutes {\n prepare: { POST(request: Request): Promise<Response> };\n activate: { POST(request: Request): Promise<Response> };\n status: { GET(request: Request): Promise<Response> };\n act: { POST(request: Request): Promise<Response> };\n revoke: { POST(request: Request): Promise<Response> };\n}\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n}\n\n/** Anything unclassified that reaches a route is an upstream failure, not our 500. */\nfunction upstream(e: unknown, op: string): PepuError {\n const err = toPepuError(e, { op });\n if (err.code === \"UNKNOWN\" && !(e instanceof PepuError)) {\n return new PepuChainError(\"UNKNOWN\", err.message, { status: 502, cause: e });\n }\n return err;\n}\n\nasync function guard(op: string, fn: () => Promise<Response>): Promise<Response> {\n try {\n return await fn();\n } catch (e) {\n return toErrorResponse(upstream(e, op));\n }\n}\n\n/** The bearer token on a request, or `\"\"`. */\nfunction bearerToken(request: Request): string {\n return (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer\\s+/i, \"\").trim();\n}\n\n/** Marker: signed in, but Privy's server does not list an embedded wallet yet. */\nconst PROVISIONING = Symbol(\"wallet-provisioning\");\n\nconst nowSeconds = (): number => Math.floor(Date.now() / 1000);\n\nfunction defaultPublicClient(): PublicClient {\n return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) }) as PublicClient;\n}\n\n/**\n * Route handlers for the Kernel session lifecycle.\n *\n * - `prepare.POST`: the server creates a fresh session key and decides the\n * expiry. The private key stays on the server; the response carries only the\n * key's address, the expiry and the scope, so the browser can ask the owner\n * for the ONE signature that grants exactly that. Calling it again replaces\n * any pending or active session (the old key is dropped).\n * - `activate.POST` `{ approval }`: checks the approval is for this user's\n * smart account and for exactly the key, scope and expiry issued in\n * `prepare`, then stores it. 409 `SESSION_NONE` when nothing is pending,\n * 410 `SESSION_EXPIRED` for an expired offer, 400 `SESSION_APPROVAL_MISMATCH`.\n * - `status.GET`: `{ active: false }` or `{ active: true, validUntil, ... }`.\n * Never returns the session key or approval.\n * - `act.POST`: signs ONE sponsored UserOperation with the session key. 409\n * `SESSION_NONE` without a live session, 429 while another action runs.\n * - `revoke.POST`: deletes the session key and approval from the server, so\n * the app can no longer act, immediately. It does NOT uninstall the\n * permission on-chain: that grant stays valid until its expiry, but only the\n * deleted key can use it and only within the scope. An on-chain uninstall is\n * an owner-signed call to the user's own account, which a paymaster\n * destination allowlist rightly does not sponsor.\n *\n * Gas: the paymaster policy service reserves worst-case cost per operation:\n * about 20.5 PEPU for a session's first operation and about 6.9 PEPU for later\n * ones (`SESSION_GAS_RESERVATION_PEPU`). Size spend caps above that. Fees come\n * from the chain with 20% headroom.\n *\n * @example\n * // lib/session-routes.ts\n * export const routes = createSponsoredSessionRoutes({\n * scope: { calls: [{ target: tapScore, abi: tapScoreAbi, functionName: \"tap\" }] },\n * store: createMemoryStore(), // DEV ONLY\n * act: {\n * parse: () => ({}),\n * buildCalls: () => [{ to: tapScore, abi: tapScoreAbi, functionName: \"tap\" }],\n * },\n * });\n * // app/api/session/prepare/route.ts: export const { POST } = routes.prepare;\n */\nexport function createSponsoredSessionRoutes<I>(o: SponsoredSessionRoutesOptions<I>): SponsoredSessionRoutes {\n // A call whose target is empty or undefined (an unset env variable) is \"not configured yet\":\n // every route then answers CONFIG_MISSING_ENV at request time. A malformed non-empty scope\n // still fails at startup, not on the first request.\n const unconfigured = o.scope.calls.some((c) => !c.target || String(c.target).trim() === \"\");\n if (unconfigured) {\n const unset = async (): Promise<Response> =>\n toErrorResponse(\n new PepuConfigError(\n \"CONFIG_MISSING_ENV\",\n `${o.scope.targetEnv ?? \"A session target contract address\"} is not set to a valid address. See .env.example.`,\n { hint: \"Set it and restart the server.\" },\n ),\n );\n return {\n prepare: { POST: unset },\n activate: { POST: unset },\n status: { GET: unset },\n act: { POST: unset },\n revoke: { POST: unset },\n };\n }\n buildKernelSessionPolicies({ calls: o.scope.calls, validUntil: 1 });\n let publicClient = o.publicClient;\n const client = (): PublicClient => (publicClient ??= defaultPublicClient());\n\n const wait = { attempts: o.provisioningWait?.attempts ?? 3, delayMs: o.provisioningWait?.delayMs ?? 400 };\n\n /**\n * Authenticate. A signed-in user whose wallet Privy's server does not list yet is looked up again (bounded), then\n * reported as `PROVISIONING` so the caller decides: `status` makes it a normal state, the rest throw a retryable 409.\n */\n const authenticateOrProvisioning = async (request: Request): Promise<ComboUser | Response | typeof PROVISIONING> => {\n if (o.authenticate) {\n const user = await o.authenticate(request);\n if (!user) throw new PepuAuthError(\"AUTH_INVALID_TOKEN\", \"Missing or invalid Privy access token.\");\n return user;\n }\n const privy = o.privy ?? createPrivyServer();\n for (let attempt = 0; ; attempt++) {\n const auth = await requireUser(request, { privy });\n if (!auth.ok) return auth.response;\n if (auth.user.address) return { userId: auth.user.userId, ownerAddress: auth.user.address };\n if (attempt >= wait.attempts) return PROVISIONING;\n await new Promise((resolve) => setTimeout(resolve, wait.delayMs * (attempt + 1)));\n }\n };\n\n const authenticate = async (request: Request): Promise<ComboUser | Response> => {\n const user = await authenticateOrProvisioning(request);\n if (user === PROVISIONING) {\n throw new PepuAuthError(\n \"WALLET_NOT_PROVISIONED\",\n \"Your wallet is still being set up. This usually takes a few seconds; retrying.\",\n { status: 409, retryable: true },\n );\n }\n return user;\n };\n\n const minutes = (): number => o.minutes ?? resolveSessionMinutes(process.env.SESSION_DURATION_MINUTES);\n const policiesFor = (validUntil: number) => buildKernelSessionPolicies({ calls: o.scope.calls, validUntil });\n\n return {\n prepare: {\n POST: (request) =>\n guard(\"combo prepare\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const { userId, ownerAddress } = user;\n const mins = minutes();\n const validUntil = sessionExpiry(nowSeconds(), mins);\n const key = generateSessionKey();\n const policies = policiesFor(validUntil);\n const [kernelAddress, permissionId] = await Promise.all([\n getKernelAddress(client(), ownerAddress),\n expectedPermissionId({ publicClient: client(), sessionKeyAddress: key.address, policies }),\n ]);\n const record: SessionRecord = {\n userId,\n ownerAddress,\n kernelAddress,\n sessionPrivateKey: key.privateKey,\n sessionKeyAddress: key.address,\n permissionId,\n validUntil,\n approval: null,\n actions: 0,\n };\n await o.store.set(record);\n return json({\n ownerAddress,\n kernelAddress,\n sessionKeyAddress: key.address,\n validUntil,\n minutes: mins,\n scope: describeKernelSessionScope({ calls: o.scope.calls, validUntil }),\n });\n }),\n },\n\n activate: {\n POST: (request) =>\n guard(\"combo activate\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const body = (await request.json().catch(() => null)) as { approval?: unknown } | null;\n if (typeof body?.approval !== \"string\") {\n throw new PepuPolicyError(\"UNKNOWN\", \"Missing approval.\", { status: 400, hint: \"Send { approval }.\" });\n }\n const record = await o.store.get(user.userId);\n if (!record || record.approval !== null) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No pending session. Start again.\");\n }\n if (nowSeconds() >= record.validUntil) {\n await o.store.delete(record.userId);\n throw new PepuSessionError(\"SESSION_EXPIRED\", \"The session offer expired. Start again.\");\n }\n const check = checkApproval(body.approval, {\n kernelAddress: record.kernelAddress,\n permissionId: record.permissionId,\n });\n if (!check.ok) throw new PepuSessionError(\"SESSION_APPROVAL_MISMATCH\", check.reason, { status: 400 });\n await o.store.set({ ...record, approval: body.approval });\n return json({ active: true, validUntil: record.validUntil });\n }),\n },\n\n status: {\n GET: (request) =>\n guard(\"combo status\", async () => {\n const user = await authenticateOrProvisioning(request);\n if (user instanceof Response) return user;\n if (user === PROVISIONING) return json({ active: false, provisioning: true });\n const record = await o.store.get(user.userId);\n if (!record || !isLive(record, nowSeconds())) return json({ active: false });\n return json({\n active: true,\n validUntil: record.validUntil,\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n sessionKeyAddress: record.sessionKeyAddress,\n actions: record.actions,\n });\n }),\n },\n\n act: {\n POST: (request) =>\n guard(\"combo act\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n const record = await o.store.get(user.userId);\n if (!record || !record.approval || !isLive(record, nowSeconds())) {\n throw new PepuSessionError(\"SESSION_NONE\", \"No active session. Start one first.\");\n }\n\n let input: I;\n try {\n input = o.act.parse(await request.json().catch(() => ({})));\n } catch (e) {\n throw new PepuPolicyError(\"UNKNOWN\", e instanceof Error ? e.message : \"Invalid request body.\", {\n status: 400,\n hint: \"Fix the request body.\",\n cause: e,\n });\n }\n const calls = o.act.buildCalls(input, {\n kernelAddress: record.kernelAddress,\n ownerAddress: record.ownerAddress,\n });\n // Fail fast; the chain is the real enforcement (see the file comment).\n assertCallsInScope(describeKernelSessionScope({ calls: o.scope.calls, validUntil: record.validUntil }), calls);\n\n if (!(await o.store.tryLock(user.userId))) {\n throw new PepuChainError(\"UNKNOWN\", \"An action is already in flight.\", {\n status: 429,\n retryable: true,\n hint: \"Wait for the current action to finish.\",\n });\n }\n const privyToken = o.forwardPrivyToken === false ? \"\" : bearerToken(request);\n try {\n const account = await loadKernelSessionAccount({\n publicClient: client(),\n approval: record.approval,\n sessionPrivateKey: record.sessionPrivateKey,\n });\n const kernel = createPepuSponsoredClient({\n account,\n publicClient: client(),\n ...(o.endpoints?.bundlerUrl !== undefined ? { bundlerUrl: o.endpoints.bundlerUrl } : {}),\n ...(o.endpoints?.paymasterUrl !== undefined ? { paymasterUrl: o.endpoints.paymasterUrl } : {}),\n ...(o.endpoints?.paymasterToken !== undefined ? { paymasterToken: o.endpoints.paymasterToken } : {}),\n ...(privyToken ? { paymasterContext: buildPaymasterContext({ privyAccessToken: privyToken }) } : {}),\n });\n const result = await sendSponsored({ client: kernel, calls });\n const actions = record.actions + (result.success ? 1 : 0);\n if (result.success) await o.store.set({ ...record, actions });\n const out: SponsoredActResult = {\n userOpHash: result.userOpHash,\n transactionHash: result.transactionHash,\n kernelAddress: record.kernelAddress,\n success: result.success,\n paymaster: result.paymaster,\n actualGasCostWei: result.actualGasCostWei.toString(),\n explorerUrl: result.explorerUrl,\n actions,\n };\n return json(out);\n } finally {\n await o.store.unlock(user.userId);\n }\n }),\n },\n\n revoke: {\n POST: (request) =>\n guard(\"combo revoke\", async () => {\n const user = await authenticate(request);\n if (user instanceof Response) return user;\n await o.store.delete(user.userId);\n return json({ active: false });\n }),\n },\n };\n}\n\n/**\n * Throws `POLICY_UNSCOPED` (403) unless every call targets an allowed contract\n * and function selector with a value within the limit. Pure; used by the act\n * route and exported for custom routes.\n *\n * @example\n * assertCallsInScope(describeKernelSessionScope({ calls, validUntil }), [{ to, abi, functionName: \"tap\" }]);\n */\nexport function assertCallsInScope(scope: Pick<KernelSessionScope, \"calls\">, calls: readonly Call[]): void {\n for (const c of normalizeCalls(calls)) {\n if (!isCallInScope(scope, c)) {\n throw new PepuPolicyError(\"POLICY_UNSCOPED\", \"A call is outside the session scope.\", {\n status: 403,\n hint: \"Only the contracts and functions the user approved can be called.\",\n });\n }\n }\n}\n"]}
|