pico-engine 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +188 -0
- package/dist/RulesetRegistryLoaderFs.js +2 -0
- package/dist/auth/AuthService.js +601 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/webauthn.js +97 -0
- package/dist/bundledKrl.js +42 -0
- package/dist/cli.js +11 -0
- package/dist/identity/IdentityService.js +340 -0
- package/dist/identity/crossPico.js +238 -0
- package/dist/identity/dbHelpers.js +67 -0
- package/dist/identity/didcommIngressRoutes.js +44 -0
- package/dist/identity/didoModule.js +252 -0
- package/dist/identity/errors.js +11 -0
- package/dist/identity/establishSubscription.js +97 -0
- package/dist/identity/index.js +15 -0
- package/dist/identity/peerDid.js +9 -0
- package/dist/identity/skyIntro.js +194 -0
- package/dist/identity/skyProtocol.js +105 -0
- package/dist/identity/store.js +233 -0
- package/dist/identity/types.js +13 -0
- package/dist/identity/veramoDidComm.js +260 -0
- package/dist/identity/webvh.js +266 -0
- package/dist/identity/webvhCrypto.js +128 -0
- package/dist/identity/webvhRoutes.js +61 -0
- package/dist/index.js +100 -44
- package/dist/oauth/OAuthService.js +388 -0
- package/dist/oauth/acg.js +495 -0
- package/dist/oauth/channelEligibility.js +26 -0
- package/dist/oauth/errors.js +12 -0
- package/dist/oauth/index.js +21 -0
- package/dist/oauth/krlModule.js +27 -0
- package/dist/oauth/meshOAuth.js +43 -0
- package/dist/provisionRoot.js +118 -0
- package/dist/server.js +609 -15
- package/dist/uiChannelPolicies.js +48 -0
- package/krl/io.picolabs.did-o.krl +5 -1
- package/krl/io.picolabs.oauth.krl +48 -0
- package/krl/io.picolabs.pico-engine-ui.krl +106 -18
- package/krl/io.picolabs.subscription.krl +242 -23
- package/krl/io.picolabs.wrangler.krl +225 -16
- package/package.json +38 -9
- package/public/docs/krl/_sidebar.md +1 -0
- package/public/docs/krl/discovery.md +144 -0
- package/public/docs/krl/modules/ctx.md +8 -0
- package/public/docs/krl/modules/event.md +41 -0
- package/public/pico-engine-ui.css +1 -1
- package/public/pico-engine-ui.js +24 -20
- package/public/pico-labs-logo.png +0 -0
- package/src/RulesetRegistryLoaderFs.ts +2 -0
- package/src/auth/AuthService.ts +850 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/webauthn.ts +182 -0
- package/src/bundledKrl.ts +42 -0
- package/src/cli.ts +11 -0
- package/src/identity/IdentityService.ts +571 -0
- package/src/identity/crossPico.ts +371 -0
- package/src/identity/dbHelpers.ts +51 -0
- package/src/identity/didcommIngressRoutes.ts +54 -0
- package/src/identity/didoModule.ts +388 -0
- package/src/identity/errors.ts +8 -0
- package/src/identity/establishSubscription.ts +160 -0
- package/src/identity/index.ts +24 -0
- package/src/identity/peerDid.ts +22 -0
- package/src/identity/skyIntro.ts +321 -0
- package/src/identity/skyProtocol.ts +192 -0
- package/src/identity/store.ts +343 -0
- package/src/identity/types.ts +63 -0
- package/src/identity/veramoDidComm.ts +363 -0
- package/src/identity/webvh.ts +325 -0
- package/src/identity/webvhCrypto.ts +200 -0
- package/src/identity/webvhRoutes.ts +64 -0
- package/src/index.ts +145 -53
- package/src/oauth/OAuthService.ts +510 -0
- package/src/oauth/acg.ts +666 -0
- package/src/oauth/channelEligibility.ts +26 -0
- package/src/oauth/errors.ts +10 -0
- package/src/oauth/index.ts +14 -0
- package/src/oauth/krlModule.ts +31 -0
- package/src/oauth/meshOAuth.ts +50 -0
- package/src/provisionRoot.ts +151 -0
- package/src/server.ts +700 -24
- package/src/uiChannelPolicies.ts +49 -0
package/src/oauth/acg.ts
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
import * as crypto from "crypto";
|
|
2
|
+
import { PicoDb, PicoDbKey, PicoFramework } from "pico-framework";
|
|
3
|
+
import { OAuthError } from "./errors";
|
|
4
|
+
import { rootHasOAuthMeshRuleset } from "./meshOAuth";
|
|
5
|
+
|
|
6
|
+
export interface OAuthTokenResponse {
|
|
7
|
+
access_token: string;
|
|
8
|
+
token_type: "Bearer";
|
|
9
|
+
expires_in?: number;
|
|
10
|
+
refresh_token?: string;
|
|
11
|
+
scope?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const OAUTH_APP_PREFIX = "oauth-app";
|
|
15
|
+
export const OAUTH_AUTH_CODE_PREFIX = "oauth-auth-code";
|
|
16
|
+
export const OAUTH_REFRESH_PREFIX = "oauth-refresh";
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_ACG_SCOPE = "mesh";
|
|
19
|
+
export const AUTH_CODE_TTL_MS = 10 * 60 * 1000;
|
|
20
|
+
export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;
|
|
21
|
+
|
|
22
|
+
export interface StoredOAuthApp {
|
|
23
|
+
clientId: string;
|
|
24
|
+
rootPicoId: string;
|
|
25
|
+
name: string;
|
|
26
|
+
redirectUris: string[];
|
|
27
|
+
publicClient: boolean;
|
|
28
|
+
secretSalt?: string;
|
|
29
|
+
secretHash?: string;
|
|
30
|
+
scopes: string[];
|
|
31
|
+
createdAt: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface OAuthAppSummary {
|
|
35
|
+
client_id: string;
|
|
36
|
+
name: string;
|
|
37
|
+
redirect_uris: string[];
|
|
38
|
+
public_client: boolean;
|
|
39
|
+
scopes: string[];
|
|
40
|
+
created_at: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface OAuthAppCredentials {
|
|
44
|
+
client_id: string;
|
|
45
|
+
client_secret?: string;
|
|
46
|
+
name: string;
|
|
47
|
+
redirect_uris: string[];
|
|
48
|
+
public_client: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface StoredAuthCode {
|
|
52
|
+
code: string;
|
|
53
|
+
clientId: string;
|
|
54
|
+
rootPicoId: string;
|
|
55
|
+
accountId: string;
|
|
56
|
+
redirectUri: string;
|
|
57
|
+
scope: string;
|
|
58
|
+
codeChallenge: string;
|
|
59
|
+
codeChallengeMethod: string;
|
|
60
|
+
expiresAt: number;
|
|
61
|
+
createdAt: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface StoredRefreshToken {
|
|
65
|
+
refreshToken: string;
|
|
66
|
+
accessToken: string;
|
|
67
|
+
clientId: string;
|
|
68
|
+
rootPicoId: string;
|
|
69
|
+
appId: string;
|
|
70
|
+
accountId: string;
|
|
71
|
+
scope: string;
|
|
72
|
+
expiresAt: number;
|
|
73
|
+
createdAt: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface AuthorizeParams {
|
|
77
|
+
client_id: string;
|
|
78
|
+
redirect_uri: string;
|
|
79
|
+
response_type: string;
|
|
80
|
+
state?: string;
|
|
81
|
+
scope?: string;
|
|
82
|
+
code_challenge: string;
|
|
83
|
+
code_challenge_method: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface ApproveParams {
|
|
87
|
+
client_id: string;
|
|
88
|
+
redirect_uri: string;
|
|
89
|
+
state?: string;
|
|
90
|
+
scope?: string;
|
|
91
|
+
code_challenge: string;
|
|
92
|
+
code_challenge_method: string;
|
|
93
|
+
approved: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function parseApproveBody(body: Record<string, unknown>): ApproveParams {
|
|
97
|
+
return {
|
|
98
|
+
client_id: String(body.client_id || "").trim(),
|
|
99
|
+
redirect_uri: String(body.redirect_uri || "").trim(),
|
|
100
|
+
state: body.state !== undefined ? String(body.state) : undefined,
|
|
101
|
+
scope: body.scope !== undefined ? String(body.scope) : undefined,
|
|
102
|
+
code_challenge: String(body.code_challenge || "").trim(),
|
|
103
|
+
code_challenge_method: String(body.code_challenge_method || "S256").trim(),
|
|
104
|
+
approved:
|
|
105
|
+
body.approved === true ||
|
|
106
|
+
String(body.approved ?? "")
|
|
107
|
+
.trim()
|
|
108
|
+
.toLowerCase() === "true",
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface AcgContext {
|
|
113
|
+
db: PicoDb;
|
|
114
|
+
pf: PicoFramework;
|
|
115
|
+
tokenTtlMs: number;
|
|
116
|
+
putAccessToken: (record: {
|
|
117
|
+
token: string;
|
|
118
|
+
rootPicoId: string;
|
|
119
|
+
appId: string;
|
|
120
|
+
accountId: string;
|
|
121
|
+
scope: string;
|
|
122
|
+
expiresAt: number;
|
|
123
|
+
}) => Promise<void>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function parseAuthorizeQuery(query: Record<string, unknown>): AuthorizeParams {
|
|
127
|
+
const client_id = String(query.client_id || "").trim();
|
|
128
|
+
const redirect_uri = String(query.redirect_uri || "").trim();
|
|
129
|
+
const response_type = String(query.response_type || "").trim();
|
|
130
|
+
const state = query.state !== undefined ? String(query.state) : undefined;
|
|
131
|
+
const scope = normalizeScope(String(query.scope || DEFAULT_ACG_SCOPE));
|
|
132
|
+
const code_challenge = String(query.code_challenge || "").trim();
|
|
133
|
+
const code_challenge_method = String(
|
|
134
|
+
query.code_challenge_method || "S256"
|
|
135
|
+
).trim();
|
|
136
|
+
|
|
137
|
+
if (!client_id || !redirect_uri || !code_challenge) {
|
|
138
|
+
throw new OAuthError("Invalid authorize request", "invalid_request", 400);
|
|
139
|
+
}
|
|
140
|
+
if (response_type !== "code") {
|
|
141
|
+
throw new OAuthError("Unsupported response_type", "unsupported_response_type", 400);
|
|
142
|
+
}
|
|
143
|
+
if (!["S256", "plain"].includes(code_challenge_method)) {
|
|
144
|
+
throw new OAuthError("Unsupported code_challenge_method", "invalid_request", 400);
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
client_id,
|
|
148
|
+
redirect_uri,
|
|
149
|
+
response_type,
|
|
150
|
+
state,
|
|
151
|
+
scope,
|
|
152
|
+
code_challenge,
|
|
153
|
+
code_challenge_method,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function listApps(
|
|
158
|
+
ctx: AcgContext,
|
|
159
|
+
rootPicoId: string
|
|
160
|
+
): Promise<OAuthAppSummary[]> {
|
|
161
|
+
assertMeshOAuthRoot(ctx, rootPicoId);
|
|
162
|
+
const rows = await dbList<StoredOAuthApp>(ctx.db, [OAUTH_APP_PREFIX]);
|
|
163
|
+
return rows
|
|
164
|
+
.filter((row) => row.value.rootPicoId === rootPicoId)
|
|
165
|
+
.map((row) => summarizeApp(row.value))
|
|
166
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function registerApp(
|
|
170
|
+
ctx: AcgContext,
|
|
171
|
+
rootPicoId: string,
|
|
172
|
+
input: {
|
|
173
|
+
name?: string;
|
|
174
|
+
redirect_uris?: string[];
|
|
175
|
+
public_client?: boolean;
|
|
176
|
+
}
|
|
177
|
+
): Promise<OAuthAppCredentials> {
|
|
178
|
+
assertMeshOAuthRoot(ctx, rootPicoId);
|
|
179
|
+
const name = (input.name || "").trim();
|
|
180
|
+
const redirectUris = normalizeRedirectUris(input.redirect_uris || []);
|
|
181
|
+
if (!name) {
|
|
182
|
+
throw new OAuthError("App name is required", "invalid_request", 400);
|
|
183
|
+
}
|
|
184
|
+
if (redirectUris.length === 0) {
|
|
185
|
+
throw new OAuthError("At least one redirect_uri is required", "invalid_request", 400);
|
|
186
|
+
}
|
|
187
|
+
const publicClient = input.public_client !== false;
|
|
188
|
+
const clientId = mintAppId();
|
|
189
|
+
let client_secret: string | undefined;
|
|
190
|
+
const record: StoredOAuthApp = {
|
|
191
|
+
clientId,
|
|
192
|
+
rootPicoId,
|
|
193
|
+
name,
|
|
194
|
+
redirectUris,
|
|
195
|
+
publicClient,
|
|
196
|
+
scopes: [DEFAULT_ACG_SCOPE],
|
|
197
|
+
createdAt: new Date().toISOString(),
|
|
198
|
+
};
|
|
199
|
+
if (!publicClient) {
|
|
200
|
+
client_secret = randomSecret();
|
|
201
|
+
const secretSalt = randomSalt();
|
|
202
|
+
record.secretSalt = secretSalt;
|
|
203
|
+
record.secretHash = hashSecret(client_secret, secretSalt);
|
|
204
|
+
}
|
|
205
|
+
await ctx.db.put([OAUTH_APP_PREFIX, clientId], record);
|
|
206
|
+
return {
|
|
207
|
+
client_id: clientId,
|
|
208
|
+
client_secret,
|
|
209
|
+
name,
|
|
210
|
+
redirect_uris: redirectUris,
|
|
211
|
+
public_client: publicClient,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function revokeApp(
|
|
216
|
+
ctx: AcgContext,
|
|
217
|
+
rootPicoId: string,
|
|
218
|
+
clientId: string
|
|
219
|
+
): Promise<void> {
|
|
220
|
+
assertMeshOAuthRoot(ctx, rootPicoId);
|
|
221
|
+
const app = await getApp(ctx, clientId);
|
|
222
|
+
if (!app || app.rootPicoId !== rootPicoId) {
|
|
223
|
+
throw new OAuthError("Unknown app", "invalid_client", 404);
|
|
224
|
+
}
|
|
225
|
+
await ctx.db.del([OAUTH_APP_PREFIX, clientId]);
|
|
226
|
+
await revokeAppTokens(ctx, clientId);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function getAppForAuthorize(
|
|
230
|
+
ctx: AcgContext,
|
|
231
|
+
params: AuthorizeParams
|
|
232
|
+
): Promise<StoredOAuthApp> {
|
|
233
|
+
const app = await getApp(ctx, params.client_id);
|
|
234
|
+
if (!app) {
|
|
235
|
+
throw new OAuthError("Unknown client", "invalid_client", 401);
|
|
236
|
+
}
|
|
237
|
+
if (!rootHasOAuthMeshRuleset(ctx.pf, app.rootPicoId)) {
|
|
238
|
+
throw new OAuthError("OAuth mesh is not enabled", "invalid_client", 401);
|
|
239
|
+
}
|
|
240
|
+
assertRedirectUri(app, params.redirect_uri);
|
|
241
|
+
if (app.publicClient && !params.code_challenge) {
|
|
242
|
+
throw new OAuthError("PKCE code_challenge is required", "invalid_request", 400);
|
|
243
|
+
}
|
|
244
|
+
return app;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function renderConsentHtml(app: StoredOAuthApp, params: AuthorizeParams): string {
|
|
248
|
+
const esc = escapeHtml;
|
|
249
|
+
const fields = [
|
|
250
|
+
["client_id", params.client_id],
|
|
251
|
+
["redirect_uri", params.redirect_uri],
|
|
252
|
+
["scope", params.scope || DEFAULT_ACG_SCOPE],
|
|
253
|
+
["code_challenge", params.code_challenge],
|
|
254
|
+
["code_challenge_method", params.code_challenge_method],
|
|
255
|
+
...(params.state !== undefined ? [["state", params.state] as [string, string]] : []),
|
|
256
|
+
];
|
|
257
|
+
const hidden = fields
|
|
258
|
+
.map(
|
|
259
|
+
([name, value]) =>
|
|
260
|
+
`<input type="hidden" name="${esc(name)}" value="${esc(value)}"/>`
|
|
261
|
+
)
|
|
262
|
+
.join("\n");
|
|
263
|
+
return `<!DOCTYPE html>
|
|
264
|
+
<html lang="en">
|
|
265
|
+
<head>
|
|
266
|
+
<meta charset="utf-8"/>
|
|
267
|
+
<title>Authorize ${esc(app.name)}</title>
|
|
268
|
+
<style>
|
|
269
|
+
body { font-family: system-ui, sans-serif; max-width: 36rem; margin: 3rem auto; padding: 0 1rem; }
|
|
270
|
+
.card { border: 1px solid #ddd; border-radius: 8px; padding: 1.25rem; }
|
|
271
|
+
.muted { color: #666; font-size: 0.9rem; }
|
|
272
|
+
.actions { margin-top: 1.25rem; display: flex; gap: 0.75rem; }
|
|
273
|
+
button { font: inherit; padding: 0.5rem 1rem; border-radius: 6px; border: 1px solid #ccc; cursor: pointer; }
|
|
274
|
+
button.primary { background: #007bff; color: #fff; border-color: #007bff; }
|
|
275
|
+
</style>
|
|
276
|
+
</head>
|
|
277
|
+
<body>
|
|
278
|
+
<div class="card">
|
|
279
|
+
<h1>Authorize application</h1>
|
|
280
|
+
<p><strong>${esc(app.name)}</strong> is requesting access to this pico mesh.</p>
|
|
281
|
+
<p class="muted">Scope: <code>${esc(params.scope || DEFAULT_ACG_SCOPE)}</code> (read and control this mesh via /sky/*)</p>
|
|
282
|
+
<p class="muted">Redirect: <code>${esc(params.redirect_uri)}</code></p>
|
|
283
|
+
<form method="POST" action="/oauth/approve">
|
|
284
|
+
${hidden}
|
|
285
|
+
<input type="hidden" name="approved" value="true"/>
|
|
286
|
+
<div class="actions">
|
|
287
|
+
<button class="primary" type="submit">Allow</button>
|
|
288
|
+
</div>
|
|
289
|
+
</form>
|
|
290
|
+
<form method="POST" action="/oauth/approve" style="margin-top:0.75rem">
|
|
291
|
+
${hidden}
|
|
292
|
+
<input type="hidden" name="approved" value="false"/>
|
|
293
|
+
<button type="submit">Deny</button>
|
|
294
|
+
</form>
|
|
295
|
+
</div>
|
|
296
|
+
</body>
|
|
297
|
+
</html>`;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export async function approveAuthorization(
|
|
301
|
+
ctx: AcgContext,
|
|
302
|
+
session: { accountId: string; rootPicoId: string },
|
|
303
|
+
params: ApproveParams
|
|
304
|
+
): Promise<string> {
|
|
305
|
+
const app = await getAppForAuthorize(ctx, {
|
|
306
|
+
client_id: params.client_id,
|
|
307
|
+
redirect_uri: params.redirect_uri,
|
|
308
|
+
response_type: "code",
|
|
309
|
+
state: params.state,
|
|
310
|
+
scope: params.scope,
|
|
311
|
+
code_challenge: params.code_challenge,
|
|
312
|
+
code_challenge_method: params.code_challenge_method,
|
|
313
|
+
});
|
|
314
|
+
if (app.rootPicoId !== session.rootPicoId) {
|
|
315
|
+
throw new OAuthError("Not authorized for this mesh", "access_denied", 403);
|
|
316
|
+
}
|
|
317
|
+
if (!params.approved) {
|
|
318
|
+
return redirectWithError(params.redirect_uri, "access_denied", params.state);
|
|
319
|
+
}
|
|
320
|
+
const code = mintAuthCode();
|
|
321
|
+
const record: StoredAuthCode = {
|
|
322
|
+
code,
|
|
323
|
+
clientId: app.clientId,
|
|
324
|
+
rootPicoId: app.rootPicoId,
|
|
325
|
+
accountId: session.accountId,
|
|
326
|
+
redirectUri: params.redirect_uri,
|
|
327
|
+
scope: normalizeScope(params.scope || DEFAULT_ACG_SCOPE),
|
|
328
|
+
codeChallenge: params.code_challenge,
|
|
329
|
+
codeChallengeMethod: params.code_challenge_method,
|
|
330
|
+
expiresAt: Date.now() + AUTH_CODE_TTL_MS,
|
|
331
|
+
createdAt: new Date().toISOString(),
|
|
332
|
+
};
|
|
333
|
+
await ctx.db.put([OAUTH_AUTH_CODE_PREFIX, code], record);
|
|
334
|
+
return redirectWithCode(params.redirect_uri, code, params.state);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export async function authorizationCodeGrant(
|
|
338
|
+
ctx: AcgContext,
|
|
339
|
+
input: {
|
|
340
|
+
grant_type?: string;
|
|
341
|
+
code?: string;
|
|
342
|
+
redirect_uri?: string;
|
|
343
|
+
client_id?: string;
|
|
344
|
+
client_secret?: string;
|
|
345
|
+
code_verifier?: string;
|
|
346
|
+
}
|
|
347
|
+
): Promise<OAuthTokenResponse & { refresh_token?: string; scope?: string }> {
|
|
348
|
+
const code = (input.code || "").trim();
|
|
349
|
+
const redirect_uri = (input.redirect_uri || "").trim();
|
|
350
|
+
const client_id = (input.client_id || "").trim();
|
|
351
|
+
const client_secret = (input.client_secret || "").trim();
|
|
352
|
+
const code_verifier = (input.code_verifier || "").trim();
|
|
353
|
+
if (!code || !redirect_uri || !client_id || !code_verifier) {
|
|
354
|
+
throw new OAuthError("Invalid token request", "invalid_request", 400);
|
|
355
|
+
}
|
|
356
|
+
const stored = await dbGet<StoredAuthCode>(ctx.db, [OAUTH_AUTH_CODE_PREFIX, code]);
|
|
357
|
+
if (!stored) {
|
|
358
|
+
throw new OAuthError("Invalid authorization code", "invalid_grant", 400);
|
|
359
|
+
}
|
|
360
|
+
if (stored.expiresAt < Date.now()) {
|
|
361
|
+
await ctx.db.del([OAUTH_AUTH_CODE_PREFIX, code]);
|
|
362
|
+
throw new OAuthError("Authorization code expired", "invalid_grant", 400);
|
|
363
|
+
}
|
|
364
|
+
if (
|
|
365
|
+
stored.clientId !== client_id ||
|
|
366
|
+
stored.redirectUri !== redirect_uri
|
|
367
|
+
) {
|
|
368
|
+
throw new OAuthError("Authorization code mismatch", "invalid_grant", 400);
|
|
369
|
+
}
|
|
370
|
+
const app = await getApp(ctx, client_id);
|
|
371
|
+
if (!app) {
|
|
372
|
+
throw new OAuthError("Invalid client", "invalid_client", 401);
|
|
373
|
+
}
|
|
374
|
+
await assertClientAuth(app, client_secret);
|
|
375
|
+
if (!verifyPkce(code_verifier, stored.codeChallenge, stored.codeChallengeMethod)) {
|
|
376
|
+
throw new OAuthError("Invalid PKCE verifier", "invalid_grant", 400);
|
|
377
|
+
}
|
|
378
|
+
await ctx.db.del([OAUTH_AUTH_CODE_PREFIX, code]);
|
|
379
|
+
return mintAcgTokens(ctx, {
|
|
380
|
+
app,
|
|
381
|
+
accountId: stored.accountId,
|
|
382
|
+
scope: stored.scope,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export async function refreshTokenGrant(
|
|
387
|
+
ctx: AcgContext,
|
|
388
|
+
input: {
|
|
389
|
+
grant_type?: string;
|
|
390
|
+
refresh_token?: string;
|
|
391
|
+
client_id?: string;
|
|
392
|
+
client_secret?: string;
|
|
393
|
+
}
|
|
394
|
+
): Promise<OAuthTokenResponse & { refresh_token?: string; scope?: string }> {
|
|
395
|
+
const refresh_token = (input.refresh_token || "").trim();
|
|
396
|
+
const client_id = (input.client_id || "").trim();
|
|
397
|
+
const client_secret = (input.client_secret || "").trim();
|
|
398
|
+
if (!refresh_token || !client_id) {
|
|
399
|
+
throw new OAuthError("Invalid refresh request", "invalid_request", 400);
|
|
400
|
+
}
|
|
401
|
+
const stored = await dbGet<StoredRefreshToken>(ctx.db, [
|
|
402
|
+
OAUTH_REFRESH_PREFIX,
|
|
403
|
+
refresh_token,
|
|
404
|
+
]);
|
|
405
|
+
if (!stored || stored.clientId !== client_id) {
|
|
406
|
+
throw new OAuthError("Invalid refresh token", "invalid_grant", 400);
|
|
407
|
+
}
|
|
408
|
+
if (stored.expiresAt < Date.now()) {
|
|
409
|
+
await ctx.db.del([OAUTH_REFRESH_PREFIX, refresh_token]);
|
|
410
|
+
throw new OAuthError("Refresh token expired", "invalid_grant", 400);
|
|
411
|
+
}
|
|
412
|
+
const app = await getApp(ctx, client_id);
|
|
413
|
+
if (!app) {
|
|
414
|
+
throw new OAuthError("Invalid client", "invalid_client", 401);
|
|
415
|
+
}
|
|
416
|
+
await assertClientAuth(app, client_secret);
|
|
417
|
+
await ctx.db.del([OAUTH_REFRESH_PREFIX, refresh_token]);
|
|
418
|
+
await ctx.db.del(["oauth-token", stored.accessToken] as PicoDbKey);
|
|
419
|
+
return mintAcgTokens(ctx, {
|
|
420
|
+
app,
|
|
421
|
+
accountId: stored.accountId,
|
|
422
|
+
scope: stored.scope,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function mintAcgTokens(
|
|
427
|
+
ctx: AcgContext,
|
|
428
|
+
input: { app: StoredOAuthApp; accountId: string; scope: string }
|
|
429
|
+
): Promise<OAuthTokenResponse & { refresh_token?: string; scope?: string }> {
|
|
430
|
+
const access_token = mintAccessToken();
|
|
431
|
+
const refresh_token = mintRefreshToken();
|
|
432
|
+
const expiresAt = Date.now() + ctx.tokenTtlMs;
|
|
433
|
+
await ctx.putAccessToken({
|
|
434
|
+
token: access_token,
|
|
435
|
+
rootPicoId: input.app.rootPicoId,
|
|
436
|
+
appId: input.app.clientId,
|
|
437
|
+
accountId: input.accountId,
|
|
438
|
+
scope: input.scope,
|
|
439
|
+
expiresAt,
|
|
440
|
+
});
|
|
441
|
+
const refreshRecord: StoredRefreshToken = {
|
|
442
|
+
refreshToken: refresh_token,
|
|
443
|
+
accessToken: access_token,
|
|
444
|
+
clientId: input.app.clientId,
|
|
445
|
+
rootPicoId: input.app.rootPicoId,
|
|
446
|
+
appId: input.app.clientId,
|
|
447
|
+
accountId: input.accountId,
|
|
448
|
+
scope: input.scope,
|
|
449
|
+
expiresAt: Date.now() + REFRESH_TOKEN_TTL_MS,
|
|
450
|
+
createdAt: new Date().toISOString(),
|
|
451
|
+
};
|
|
452
|
+
await ctx.db.put([OAUTH_REFRESH_PREFIX, refresh_token], refreshRecord);
|
|
453
|
+
return {
|
|
454
|
+
access_token,
|
|
455
|
+
token_type: "Bearer",
|
|
456
|
+
expires_in: Math.floor(ctx.tokenTtlMs / 1000),
|
|
457
|
+
refresh_token,
|
|
458
|
+
scope: input.scope,
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function assertMeshOAuthRoot(ctx: AcgContext, rootPicoId: string): void {
|
|
463
|
+
if (!rootHasOAuthMeshRuleset(ctx.pf, rootPicoId)) {
|
|
464
|
+
throw new OAuthError(
|
|
465
|
+
"Install io.picolabs.oauth on the root pico first",
|
|
466
|
+
"invalid_request",
|
|
467
|
+
400
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async function getApp(
|
|
473
|
+
ctx: AcgContext,
|
|
474
|
+
clientId: string
|
|
475
|
+
): Promise<StoredOAuthApp | null> {
|
|
476
|
+
return dbGet<StoredOAuthApp>(ctx.db, [OAUTH_APP_PREFIX, clientId]);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function summarizeApp(app: StoredOAuthApp): OAuthAppSummary {
|
|
480
|
+
return {
|
|
481
|
+
client_id: app.clientId,
|
|
482
|
+
name: app.name,
|
|
483
|
+
redirect_uris: app.redirectUris.slice(),
|
|
484
|
+
public_client: app.publicClient,
|
|
485
|
+
scopes: app.scopes.slice(),
|
|
486
|
+
created_at: app.createdAt,
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function assertRedirectUri(app: StoredOAuthApp, redirectUri: string): void {
|
|
491
|
+
if (!app.redirectUris.includes(redirectUri)) {
|
|
492
|
+
throw new OAuthError("Invalid redirect_uri", "invalid_request", 400);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function assertClientAuth(
|
|
497
|
+
app: StoredOAuthApp,
|
|
498
|
+
clientSecret: string
|
|
499
|
+
): Promise<void> {
|
|
500
|
+
if (app.publicClient) {
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (!clientSecret || !app.secretSalt || !app.secretHash) {
|
|
504
|
+
throw new OAuthError("Client authentication required", "invalid_client", 401);
|
|
505
|
+
}
|
|
506
|
+
if (!verifySecret(clientSecret, app.secretSalt, app.secretHash)) {
|
|
507
|
+
throw new OAuthError("Invalid client", "invalid_client", 401);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async function revokeAppTokens(ctx: AcgContext, clientId: string): Promise<void> {
|
|
512
|
+
const tokens = await dbList<{ grant?: string; appId?: string; channelEci?: string }>(
|
|
513
|
+
ctx.db,
|
|
514
|
+
["oauth-token"]
|
|
515
|
+
);
|
|
516
|
+
for (const row of tokens) {
|
|
517
|
+
if (row.value.appId === clientId) {
|
|
518
|
+
await ctx.db.del(row.key);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
const refreshes = await dbList<StoredRefreshToken>(ctx.db, [OAUTH_REFRESH_PREFIX]);
|
|
522
|
+
for (const row of refreshes) {
|
|
523
|
+
if (row.value.clientId === clientId) {
|
|
524
|
+
await ctx.db.del(row.key);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function verifyPkce(
|
|
530
|
+
verifier: string,
|
|
531
|
+
challenge: string,
|
|
532
|
+
method: string
|
|
533
|
+
): boolean {
|
|
534
|
+
if (method === "plain") {
|
|
535
|
+
return verifier === challenge;
|
|
536
|
+
}
|
|
537
|
+
if (method === "S256") {
|
|
538
|
+
const digest = crypto
|
|
539
|
+
.createHash("sha256")
|
|
540
|
+
.update(verifier)
|
|
541
|
+
.digest("base64url");
|
|
542
|
+
return digest === challenge;
|
|
543
|
+
}
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function redirectWithCode(redirectUri: string, code: string, state?: string): string {
|
|
548
|
+
const url = new URL(redirectUri);
|
|
549
|
+
url.searchParams.set("code", code);
|
|
550
|
+
if (state !== undefined) {
|
|
551
|
+
url.searchParams.set("state", state);
|
|
552
|
+
}
|
|
553
|
+
return url.toString();
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function redirectWithError(
|
|
557
|
+
redirectUri: string,
|
|
558
|
+
error: string,
|
|
559
|
+
state?: string
|
|
560
|
+
): string {
|
|
561
|
+
const url = new URL(redirectUri);
|
|
562
|
+
url.searchParams.set("error", error);
|
|
563
|
+
if (state !== undefined) {
|
|
564
|
+
url.searchParams.set("state", state);
|
|
565
|
+
}
|
|
566
|
+
return url.toString();
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function normalizeScope(scope: string): string {
|
|
570
|
+
const trimmed = (scope || DEFAULT_ACG_SCOPE).trim();
|
|
571
|
+
return trimmed || DEFAULT_ACG_SCOPE;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function normalizeRedirectUris(uris: string[]): string[] {
|
|
575
|
+
const out: string[] = [];
|
|
576
|
+
for (const raw of uris) {
|
|
577
|
+
const uri = (raw || "").trim();
|
|
578
|
+
if (!uri) {
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
let parsed: URL;
|
|
582
|
+
try {
|
|
583
|
+
parsed = new URL(uri);
|
|
584
|
+
} catch {
|
|
585
|
+
throw new OAuthError(`Invalid redirect_uri: ${uri}`, "invalid_request", 400);
|
|
586
|
+
}
|
|
587
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
588
|
+
throw new OAuthError(`Invalid redirect_uri: ${uri}`, "invalid_request", 400);
|
|
589
|
+
}
|
|
590
|
+
if (!out.includes(uri)) {
|
|
591
|
+
out.push(uri);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return out;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function mintAppId(): string {
|
|
598
|
+
return "app_" + crypto.randomBytes(16).toString("base64url");
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function mintAuthCode(): string {
|
|
602
|
+
return "oac_" + crypto.randomBytes(32).toString("base64url");
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
export function mintAccessToken(): string {
|
|
606
|
+
return "oat_" + crypto.randomBytes(32).toString("base64url");
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function mintRefreshToken(): string {
|
|
610
|
+
return "ort_" + crypto.randomBytes(32).toString("base64url");
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function randomSecret(): string {
|
|
614
|
+
return crypto.randomBytes(32).toString("base64url");
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function randomSalt(): string {
|
|
618
|
+
return crypto.randomBytes(16).toString("base64url");
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function hashSecret(secret: string, salt: string): string {
|
|
622
|
+
return crypto.createHash("sha256").update(salt + secret).digest("base64url");
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function verifySecret(secret: string, salt: string, expected: string): boolean {
|
|
626
|
+
const actual = hashSecret(secret, salt);
|
|
627
|
+
if (actual.length !== expected.length) {
|
|
628
|
+
return false;
|
|
629
|
+
}
|
|
630
|
+
return crypto.timingSafeEqual(Buffer.from(actual), Buffer.from(expected));
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
function escapeHtml(value: string): string {
|
|
634
|
+
return value
|
|
635
|
+
.replace(/&/g, "&")
|
|
636
|
+
.replace(/</g, "<")
|
|
637
|
+
.replace(/>/g, ">")
|
|
638
|
+
.replace(/"/g, """);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
async function dbGet<T>(db: PicoDb, key: PicoDbKey): Promise<T | null> {
|
|
642
|
+
try {
|
|
643
|
+
const value = await db.get(key);
|
|
644
|
+
return value === undefined ? null : (value as T);
|
|
645
|
+
} catch (err: any) {
|
|
646
|
+
if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
throw err;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function dbList<T = any>(
|
|
654
|
+
db: PicoDb,
|
|
655
|
+
prefix: PicoDbKey
|
|
656
|
+
): Promise<{ key: PicoDbKey; value: T }[]> {
|
|
657
|
+
const out: { key: PicoDbKey; value: T }[] = [];
|
|
658
|
+
const iter = db.iterator({
|
|
659
|
+
gte: prefix,
|
|
660
|
+
lte: prefix.concat([undefined] as any),
|
|
661
|
+
});
|
|
662
|
+
for await (const [key, value] of iter) {
|
|
663
|
+
out.push({ key, value });
|
|
664
|
+
}
|
|
665
|
+
return out;
|
|
666
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ChannelReadOnly } from "pico-framework";
|
|
2
|
+
|
|
3
|
+
export const OAUTH_WEBHOOK_TAG = "oauth-webhook";
|
|
4
|
+
|
|
5
|
+
const SUBSCRIPTION_CHANNEL_TAGS = new Set([
|
|
6
|
+
"wellknown_rx",
|
|
7
|
+
"tx_rx",
|
|
8
|
+
"subscription",
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
export function isSubscriptionChannel(tags: string[]): boolean {
|
|
12
|
+
return tags.some((tag) => SUBSCRIPTION_CHANNEL_TAGS.has(tag.toLowerCase()));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isOAuthEligibleChannel(channel: ChannelReadOnly): boolean {
|
|
16
|
+
if (channel.familyChannelPicoID) {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
if (channel.tags.includes("system")) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
if (isSubscriptionChannel(channel.tags)) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return channel.tags.includes(OAUTH_WEBHOOK_TAG);
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export class OAuthError extends Error {
|
|
2
|
+
statusCode: number;
|
|
3
|
+
oauthError: string;
|
|
4
|
+
constructor(message: string, oauthError: string, statusCode = 400) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "OAuthError";
|
|
7
|
+
this.oauthError = oauthError;
|
|
8
|
+
this.statusCode = statusCode;
|
|
9
|
+
}
|
|
10
|
+
}
|