pico-engine 1.4.0 → 1.5.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.
@@ -0,0 +1,495 @@
1
+ "use strict";
2
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
3
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
+ var m = o[Symbol.asyncIterator], i;
5
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.REFRESH_TOKEN_TTL_MS = exports.AUTH_CODE_TTL_MS = exports.DEFAULT_ACG_SCOPE = exports.OAUTH_REFRESH_PREFIX = exports.OAUTH_AUTH_CODE_PREFIX = exports.OAUTH_APP_PREFIX = void 0;
11
+ exports.parseApproveBody = parseApproveBody;
12
+ exports.parseAuthorizeQuery = parseAuthorizeQuery;
13
+ exports.listApps = listApps;
14
+ exports.registerApp = registerApp;
15
+ exports.revokeApp = revokeApp;
16
+ exports.getAppForAuthorize = getAppForAuthorize;
17
+ exports.renderConsentHtml = renderConsentHtml;
18
+ exports.approveAuthorization = approveAuthorization;
19
+ exports.authorizationCodeGrant = authorizationCodeGrant;
20
+ exports.refreshTokenGrant = refreshTokenGrant;
21
+ exports.mintAccessToken = mintAccessToken;
22
+ const crypto = require("crypto");
23
+ const errors_1 = require("./errors");
24
+ const meshOAuth_1 = require("./meshOAuth");
25
+ exports.OAUTH_APP_PREFIX = "oauth-app";
26
+ exports.OAUTH_AUTH_CODE_PREFIX = "oauth-auth-code";
27
+ exports.OAUTH_REFRESH_PREFIX = "oauth-refresh";
28
+ exports.DEFAULT_ACG_SCOPE = "mesh";
29
+ exports.AUTH_CODE_TTL_MS = 10 * 60 * 1000;
30
+ exports.REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;
31
+ function parseApproveBody(body) {
32
+ var _a;
33
+ return {
34
+ client_id: String(body.client_id || "").trim(),
35
+ redirect_uri: String(body.redirect_uri || "").trim(),
36
+ state: body.state !== undefined ? String(body.state) : undefined,
37
+ scope: body.scope !== undefined ? String(body.scope) : undefined,
38
+ code_challenge: String(body.code_challenge || "").trim(),
39
+ code_challenge_method: String(body.code_challenge_method || "S256").trim(),
40
+ approved: body.approved === true ||
41
+ String((_a = body.approved) !== null && _a !== void 0 ? _a : "")
42
+ .trim()
43
+ .toLowerCase() === "true",
44
+ };
45
+ }
46
+ function parseAuthorizeQuery(query) {
47
+ const client_id = String(query.client_id || "").trim();
48
+ const redirect_uri = String(query.redirect_uri || "").trim();
49
+ const response_type = String(query.response_type || "").trim();
50
+ const state = query.state !== undefined ? String(query.state) : undefined;
51
+ const scope = normalizeScope(String(query.scope || exports.DEFAULT_ACG_SCOPE));
52
+ const code_challenge = String(query.code_challenge || "").trim();
53
+ const code_challenge_method = String(query.code_challenge_method || "S256").trim();
54
+ if (!client_id || !redirect_uri || !code_challenge) {
55
+ throw new errors_1.OAuthError("Invalid authorize request", "invalid_request", 400);
56
+ }
57
+ if (response_type !== "code") {
58
+ throw new errors_1.OAuthError("Unsupported response_type", "unsupported_response_type", 400);
59
+ }
60
+ if (!["S256", "plain"].includes(code_challenge_method)) {
61
+ throw new errors_1.OAuthError("Unsupported code_challenge_method", "invalid_request", 400);
62
+ }
63
+ return {
64
+ client_id,
65
+ redirect_uri,
66
+ response_type,
67
+ state,
68
+ scope,
69
+ code_challenge,
70
+ code_challenge_method,
71
+ };
72
+ }
73
+ async function listApps(ctx, rootPicoId) {
74
+ assertMeshOAuthRoot(ctx, rootPicoId);
75
+ const rows = await dbList(ctx.db, [exports.OAUTH_APP_PREFIX]);
76
+ return rows
77
+ .filter((row) => row.value.rootPicoId === rootPicoId)
78
+ .map((row) => summarizeApp(row.value))
79
+ .sort((a, b) => a.name.localeCompare(b.name));
80
+ }
81
+ async function registerApp(ctx, rootPicoId, input) {
82
+ assertMeshOAuthRoot(ctx, rootPicoId);
83
+ const name = (input.name || "").trim();
84
+ const redirectUris = normalizeRedirectUris(input.redirect_uris || []);
85
+ if (!name) {
86
+ throw new errors_1.OAuthError("App name is required", "invalid_request", 400);
87
+ }
88
+ if (redirectUris.length === 0) {
89
+ throw new errors_1.OAuthError("At least one redirect_uri is required", "invalid_request", 400);
90
+ }
91
+ const publicClient = input.public_client !== false;
92
+ const clientId = mintAppId();
93
+ let client_secret;
94
+ const record = {
95
+ clientId,
96
+ rootPicoId,
97
+ name,
98
+ redirectUris,
99
+ publicClient,
100
+ scopes: [exports.DEFAULT_ACG_SCOPE],
101
+ createdAt: new Date().toISOString(),
102
+ };
103
+ if (!publicClient) {
104
+ client_secret = randomSecret();
105
+ const secretSalt = randomSalt();
106
+ record.secretSalt = secretSalt;
107
+ record.secretHash = hashSecret(client_secret, secretSalt);
108
+ }
109
+ await ctx.db.put([exports.OAUTH_APP_PREFIX, clientId], record);
110
+ return {
111
+ client_id: clientId,
112
+ client_secret,
113
+ name,
114
+ redirect_uris: redirectUris,
115
+ public_client: publicClient,
116
+ };
117
+ }
118
+ async function revokeApp(ctx, rootPicoId, clientId) {
119
+ assertMeshOAuthRoot(ctx, rootPicoId);
120
+ const app = await getApp(ctx, clientId);
121
+ if (!app || app.rootPicoId !== rootPicoId) {
122
+ throw new errors_1.OAuthError("Unknown app", "invalid_client", 404);
123
+ }
124
+ await ctx.db.del([exports.OAUTH_APP_PREFIX, clientId]);
125
+ await revokeAppTokens(ctx, clientId);
126
+ }
127
+ async function getAppForAuthorize(ctx, params) {
128
+ const app = await getApp(ctx, params.client_id);
129
+ if (!app) {
130
+ throw new errors_1.OAuthError("Unknown client", "invalid_client", 401);
131
+ }
132
+ if (!(0, meshOAuth_1.rootHasOAuthMeshRuleset)(ctx.pf, app.rootPicoId)) {
133
+ throw new errors_1.OAuthError("OAuth mesh is not enabled", "invalid_client", 401);
134
+ }
135
+ assertRedirectUri(app, params.redirect_uri);
136
+ if (app.publicClient && !params.code_challenge) {
137
+ throw new errors_1.OAuthError("PKCE code_challenge is required", "invalid_request", 400);
138
+ }
139
+ return app;
140
+ }
141
+ function renderConsentHtml(app, params) {
142
+ const esc = escapeHtml;
143
+ const fields = [
144
+ ["client_id", params.client_id],
145
+ ["redirect_uri", params.redirect_uri],
146
+ ["scope", params.scope || exports.DEFAULT_ACG_SCOPE],
147
+ ["code_challenge", params.code_challenge],
148
+ ["code_challenge_method", params.code_challenge_method],
149
+ ...(params.state !== undefined ? [["state", params.state]] : []),
150
+ ];
151
+ const hidden = fields
152
+ .map(([name, value]) => `<input type="hidden" name="${esc(name)}" value="${esc(value)}"/>`)
153
+ .join("\n");
154
+ return `<!DOCTYPE html>
155
+ <html lang="en">
156
+ <head>
157
+ <meta charset="utf-8"/>
158
+ <title>Authorize ${esc(app.name)}</title>
159
+ <style>
160
+ body { font-family: system-ui, sans-serif; max-width: 36rem; margin: 3rem auto; padding: 0 1rem; }
161
+ .card { border: 1px solid #ddd; border-radius: 8px; padding: 1.25rem; }
162
+ .muted { color: #666; font-size: 0.9rem; }
163
+ .actions { margin-top: 1.25rem; display: flex; gap: 0.75rem; }
164
+ button { font: inherit; padding: 0.5rem 1rem; border-radius: 6px; border: 1px solid #ccc; cursor: pointer; }
165
+ button.primary { background: #007bff; color: #fff; border-color: #007bff; }
166
+ </style>
167
+ </head>
168
+ <body>
169
+ <div class="card">
170
+ <h1>Authorize application</h1>
171
+ <p><strong>${esc(app.name)}</strong> is requesting access to this pico mesh.</p>
172
+ <p class="muted">Scope: <code>${esc(params.scope || exports.DEFAULT_ACG_SCOPE)}</code> (read and control this mesh via /sky/*)</p>
173
+ <p class="muted">Redirect: <code>${esc(params.redirect_uri)}</code></p>
174
+ <form method="POST" action="/oauth/approve">
175
+ ${hidden}
176
+ <input type="hidden" name="approved" value="true"/>
177
+ <div class="actions">
178
+ <button class="primary" type="submit">Allow</button>
179
+ </div>
180
+ </form>
181
+ <form method="POST" action="/oauth/approve" style="margin-top:0.75rem">
182
+ ${hidden}
183
+ <input type="hidden" name="approved" value="false"/>
184
+ <button type="submit">Deny</button>
185
+ </form>
186
+ </div>
187
+ </body>
188
+ </html>`;
189
+ }
190
+ async function approveAuthorization(ctx, session, params) {
191
+ const app = await getAppForAuthorize(ctx, {
192
+ client_id: params.client_id,
193
+ redirect_uri: params.redirect_uri,
194
+ response_type: "code",
195
+ state: params.state,
196
+ scope: params.scope,
197
+ code_challenge: params.code_challenge,
198
+ code_challenge_method: params.code_challenge_method,
199
+ });
200
+ if (app.rootPicoId !== session.rootPicoId) {
201
+ throw new errors_1.OAuthError("Not authorized for this mesh", "access_denied", 403);
202
+ }
203
+ if (!params.approved) {
204
+ return redirectWithError(params.redirect_uri, "access_denied", params.state);
205
+ }
206
+ const code = mintAuthCode();
207
+ const record = {
208
+ code,
209
+ clientId: app.clientId,
210
+ rootPicoId: app.rootPicoId,
211
+ accountId: session.accountId,
212
+ redirectUri: params.redirect_uri,
213
+ scope: normalizeScope(params.scope || exports.DEFAULT_ACG_SCOPE),
214
+ codeChallenge: params.code_challenge,
215
+ codeChallengeMethod: params.code_challenge_method,
216
+ expiresAt: Date.now() + exports.AUTH_CODE_TTL_MS,
217
+ createdAt: new Date().toISOString(),
218
+ };
219
+ await ctx.db.put([exports.OAUTH_AUTH_CODE_PREFIX, code], record);
220
+ return redirectWithCode(params.redirect_uri, code, params.state);
221
+ }
222
+ async function authorizationCodeGrant(ctx, input) {
223
+ const code = (input.code || "").trim();
224
+ const redirect_uri = (input.redirect_uri || "").trim();
225
+ const client_id = (input.client_id || "").trim();
226
+ const client_secret = (input.client_secret || "").trim();
227
+ const code_verifier = (input.code_verifier || "").trim();
228
+ if (!code || !redirect_uri || !client_id || !code_verifier) {
229
+ throw new errors_1.OAuthError("Invalid token request", "invalid_request", 400);
230
+ }
231
+ const stored = await dbGet(ctx.db, [exports.OAUTH_AUTH_CODE_PREFIX, code]);
232
+ if (!stored) {
233
+ throw new errors_1.OAuthError("Invalid authorization code", "invalid_grant", 400);
234
+ }
235
+ if (stored.expiresAt < Date.now()) {
236
+ await ctx.db.del([exports.OAUTH_AUTH_CODE_PREFIX, code]);
237
+ throw new errors_1.OAuthError("Authorization code expired", "invalid_grant", 400);
238
+ }
239
+ if (stored.clientId !== client_id ||
240
+ stored.redirectUri !== redirect_uri) {
241
+ throw new errors_1.OAuthError("Authorization code mismatch", "invalid_grant", 400);
242
+ }
243
+ const app = await getApp(ctx, client_id);
244
+ if (!app) {
245
+ throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
246
+ }
247
+ await assertClientAuth(app, client_secret);
248
+ if (!verifyPkce(code_verifier, stored.codeChallenge, stored.codeChallengeMethod)) {
249
+ throw new errors_1.OAuthError("Invalid PKCE verifier", "invalid_grant", 400);
250
+ }
251
+ await ctx.db.del([exports.OAUTH_AUTH_CODE_PREFIX, code]);
252
+ return mintAcgTokens(ctx, {
253
+ app,
254
+ accountId: stored.accountId,
255
+ scope: stored.scope,
256
+ });
257
+ }
258
+ async function refreshTokenGrant(ctx, input) {
259
+ const refresh_token = (input.refresh_token || "").trim();
260
+ const client_id = (input.client_id || "").trim();
261
+ const client_secret = (input.client_secret || "").trim();
262
+ if (!refresh_token || !client_id) {
263
+ throw new errors_1.OAuthError("Invalid refresh request", "invalid_request", 400);
264
+ }
265
+ const stored = await dbGet(ctx.db, [
266
+ exports.OAUTH_REFRESH_PREFIX,
267
+ refresh_token,
268
+ ]);
269
+ if (!stored || stored.clientId !== client_id) {
270
+ throw new errors_1.OAuthError("Invalid refresh token", "invalid_grant", 400);
271
+ }
272
+ if (stored.expiresAt < Date.now()) {
273
+ await ctx.db.del([exports.OAUTH_REFRESH_PREFIX, refresh_token]);
274
+ throw new errors_1.OAuthError("Refresh token expired", "invalid_grant", 400);
275
+ }
276
+ const app = await getApp(ctx, client_id);
277
+ if (!app) {
278
+ throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
279
+ }
280
+ await assertClientAuth(app, client_secret);
281
+ await ctx.db.del([exports.OAUTH_REFRESH_PREFIX, refresh_token]);
282
+ await ctx.db.del(["oauth-token", stored.accessToken]);
283
+ return mintAcgTokens(ctx, {
284
+ app,
285
+ accountId: stored.accountId,
286
+ scope: stored.scope,
287
+ });
288
+ }
289
+ async function mintAcgTokens(ctx, input) {
290
+ const access_token = mintAccessToken();
291
+ const refresh_token = mintRefreshToken();
292
+ const expiresAt = Date.now() + ctx.tokenTtlMs;
293
+ await ctx.putAccessToken({
294
+ token: access_token,
295
+ rootPicoId: input.app.rootPicoId,
296
+ appId: input.app.clientId,
297
+ accountId: input.accountId,
298
+ scope: input.scope,
299
+ expiresAt,
300
+ });
301
+ const refreshRecord = {
302
+ refreshToken: refresh_token,
303
+ accessToken: access_token,
304
+ clientId: input.app.clientId,
305
+ rootPicoId: input.app.rootPicoId,
306
+ appId: input.app.clientId,
307
+ accountId: input.accountId,
308
+ scope: input.scope,
309
+ expiresAt: Date.now() + exports.REFRESH_TOKEN_TTL_MS,
310
+ createdAt: new Date().toISOString(),
311
+ };
312
+ await ctx.db.put([exports.OAUTH_REFRESH_PREFIX, refresh_token], refreshRecord);
313
+ return {
314
+ access_token,
315
+ token_type: "Bearer",
316
+ expires_in: Math.floor(ctx.tokenTtlMs / 1000),
317
+ refresh_token,
318
+ scope: input.scope,
319
+ };
320
+ }
321
+ function assertMeshOAuthRoot(ctx, rootPicoId) {
322
+ if (!(0, meshOAuth_1.rootHasOAuthMeshRuleset)(ctx.pf, rootPicoId)) {
323
+ throw new errors_1.OAuthError("Install io.picolabs.oauth on the root pico first", "invalid_request", 400);
324
+ }
325
+ }
326
+ async function getApp(ctx, clientId) {
327
+ return dbGet(ctx.db, [exports.OAUTH_APP_PREFIX, clientId]);
328
+ }
329
+ function summarizeApp(app) {
330
+ return {
331
+ client_id: app.clientId,
332
+ name: app.name,
333
+ redirect_uris: app.redirectUris.slice(),
334
+ public_client: app.publicClient,
335
+ scopes: app.scopes.slice(),
336
+ created_at: app.createdAt,
337
+ };
338
+ }
339
+ function assertRedirectUri(app, redirectUri) {
340
+ if (!app.redirectUris.includes(redirectUri)) {
341
+ throw new errors_1.OAuthError("Invalid redirect_uri", "invalid_request", 400);
342
+ }
343
+ }
344
+ async function assertClientAuth(app, clientSecret) {
345
+ if (app.publicClient) {
346
+ return;
347
+ }
348
+ if (!clientSecret || !app.secretSalt || !app.secretHash) {
349
+ throw new errors_1.OAuthError("Client authentication required", "invalid_client", 401);
350
+ }
351
+ if (!verifySecret(clientSecret, app.secretSalt, app.secretHash)) {
352
+ throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
353
+ }
354
+ }
355
+ async function revokeAppTokens(ctx, clientId) {
356
+ const tokens = await dbList(ctx.db, ["oauth-token"]);
357
+ for (const row of tokens) {
358
+ if (row.value.appId === clientId) {
359
+ await ctx.db.del(row.key);
360
+ }
361
+ }
362
+ const refreshes = await dbList(ctx.db, [exports.OAUTH_REFRESH_PREFIX]);
363
+ for (const row of refreshes) {
364
+ if (row.value.clientId === clientId) {
365
+ await ctx.db.del(row.key);
366
+ }
367
+ }
368
+ }
369
+ function verifyPkce(verifier, challenge, method) {
370
+ if (method === "plain") {
371
+ return verifier === challenge;
372
+ }
373
+ if (method === "S256") {
374
+ const digest = crypto
375
+ .createHash("sha256")
376
+ .update(verifier)
377
+ .digest("base64url");
378
+ return digest === challenge;
379
+ }
380
+ return false;
381
+ }
382
+ function redirectWithCode(redirectUri, code, state) {
383
+ const url = new URL(redirectUri);
384
+ url.searchParams.set("code", code);
385
+ if (state !== undefined) {
386
+ url.searchParams.set("state", state);
387
+ }
388
+ return url.toString();
389
+ }
390
+ function redirectWithError(redirectUri, error, state) {
391
+ const url = new URL(redirectUri);
392
+ url.searchParams.set("error", error);
393
+ if (state !== undefined) {
394
+ url.searchParams.set("state", state);
395
+ }
396
+ return url.toString();
397
+ }
398
+ function normalizeScope(scope) {
399
+ const trimmed = (scope || exports.DEFAULT_ACG_SCOPE).trim();
400
+ return trimmed || exports.DEFAULT_ACG_SCOPE;
401
+ }
402
+ function normalizeRedirectUris(uris) {
403
+ const out = [];
404
+ for (const raw of uris) {
405
+ const uri = (raw || "").trim();
406
+ if (!uri) {
407
+ continue;
408
+ }
409
+ let parsed;
410
+ try {
411
+ parsed = new URL(uri);
412
+ }
413
+ catch (_a) {
414
+ throw new errors_1.OAuthError(`Invalid redirect_uri: ${uri}`, "invalid_request", 400);
415
+ }
416
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
417
+ throw new errors_1.OAuthError(`Invalid redirect_uri: ${uri}`, "invalid_request", 400);
418
+ }
419
+ if (!out.includes(uri)) {
420
+ out.push(uri);
421
+ }
422
+ }
423
+ return out;
424
+ }
425
+ function mintAppId() {
426
+ return "app_" + crypto.randomBytes(16).toString("base64url");
427
+ }
428
+ function mintAuthCode() {
429
+ return "oac_" + crypto.randomBytes(32).toString("base64url");
430
+ }
431
+ function mintAccessToken() {
432
+ return "oat_" + crypto.randomBytes(32).toString("base64url");
433
+ }
434
+ function mintRefreshToken() {
435
+ return "ort_" + crypto.randomBytes(32).toString("base64url");
436
+ }
437
+ function randomSecret() {
438
+ return crypto.randomBytes(32).toString("base64url");
439
+ }
440
+ function randomSalt() {
441
+ return crypto.randomBytes(16).toString("base64url");
442
+ }
443
+ function hashSecret(secret, salt) {
444
+ return crypto.createHash("sha256").update(salt + secret).digest("base64url");
445
+ }
446
+ function verifySecret(secret, salt, expected) {
447
+ const actual = hashSecret(secret, salt);
448
+ if (actual.length !== expected.length) {
449
+ return false;
450
+ }
451
+ return crypto.timingSafeEqual(Buffer.from(actual), Buffer.from(expected));
452
+ }
453
+ function escapeHtml(value) {
454
+ return value
455
+ .replace(/&/g, "&amp;")
456
+ .replace(/</g, "&lt;")
457
+ .replace(/>/g, "&gt;")
458
+ .replace(/"/g, "&quot;");
459
+ }
460
+ async function dbGet(db, key) {
461
+ try {
462
+ const value = await db.get(key);
463
+ return value === undefined ? null : value;
464
+ }
465
+ catch (err) {
466
+ if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
467
+ return null;
468
+ }
469
+ throw err;
470
+ }
471
+ }
472
+ async function dbList(db, prefix) {
473
+ var _a, e_1, _b, _c;
474
+ const out = [];
475
+ const iter = db.iterator({
476
+ gte: prefix,
477
+ lte: prefix.concat([undefined]),
478
+ });
479
+ try {
480
+ for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = await iter_1.next(), _a = iter_1_1.done, !_a; _d = true) {
481
+ _c = iter_1_1.value;
482
+ _d = false;
483
+ const [key, value] = _c;
484
+ out.push({ key, value });
485
+ }
486
+ }
487
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
488
+ finally {
489
+ try {
490
+ if (!_d && !_a && (_b = iter_1.return)) await _b.call(iter_1);
491
+ }
492
+ finally { if (e_1) throw e_1.error; }
493
+ }
494
+ return out;
495
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAUTH_WEBHOOK_TAG = void 0;
4
+ exports.isSubscriptionChannel = isSubscriptionChannel;
5
+ exports.isOAuthEligibleChannel = isOAuthEligibleChannel;
6
+ exports.OAUTH_WEBHOOK_TAG = "oauth-webhook";
7
+ const SUBSCRIPTION_CHANNEL_TAGS = new Set([
8
+ "wellknown_rx",
9
+ "tx_rx",
10
+ "subscription",
11
+ ]);
12
+ function isSubscriptionChannel(tags) {
13
+ return tags.some((tag) => SUBSCRIPTION_CHANNEL_TAGS.has(tag.toLowerCase()));
14
+ }
15
+ function isOAuthEligibleChannel(channel) {
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(exports.OAUTH_WEBHOOK_TAG);
26
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAuthError = void 0;
4
+ class OAuthError extends Error {
5
+ constructor(message, oauthError, statusCode = 400) {
6
+ super(message);
7
+ this.name = "OAuthError";
8
+ this.oauthError = oauthError;
9
+ this.statusCode = statusCode;
10
+ }
11
+ }
12
+ exports.OAuthError = OAuthError;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initOAuthModule = exports.isChannelUnderRoot = exports.rootPicoIdForChannelEci = exports.rootHasOAuthMeshRuleset = exports.meshRequiresOAuth = exports.OAUTH_MESH_RULESET_RID = exports.isSubscriptionChannel = exports.isOAuthEligibleChannel = exports.OAUTH_WEBHOOK_TAG = exports.renderConsentHtml = exports.parseAuthorizeQuery = exports.parseApproveBody = exports.OAuthError = exports.OAuthService = void 0;
4
+ var OAuthService_1 = require("./OAuthService");
5
+ Object.defineProperty(exports, "OAuthService", { enumerable: true, get: function () { return OAuthService_1.OAuthService; } });
6
+ Object.defineProperty(exports, "OAuthError", { enumerable: true, get: function () { return OAuthService_1.OAuthError; } });
7
+ Object.defineProperty(exports, "parseApproveBody", { enumerable: true, get: function () { return OAuthService_1.parseApproveBody; } });
8
+ Object.defineProperty(exports, "parseAuthorizeQuery", { enumerable: true, get: function () { return OAuthService_1.parseAuthorizeQuery; } });
9
+ Object.defineProperty(exports, "renderConsentHtml", { enumerable: true, get: function () { return OAuthService_1.renderConsentHtml; } });
10
+ var channelEligibility_1 = require("./channelEligibility");
11
+ Object.defineProperty(exports, "OAUTH_WEBHOOK_TAG", { enumerable: true, get: function () { return channelEligibility_1.OAUTH_WEBHOOK_TAG; } });
12
+ Object.defineProperty(exports, "isOAuthEligibleChannel", { enumerable: true, get: function () { return channelEligibility_1.isOAuthEligibleChannel; } });
13
+ Object.defineProperty(exports, "isSubscriptionChannel", { enumerable: true, get: function () { return channelEligibility_1.isSubscriptionChannel; } });
14
+ var meshOAuth_1 = require("./meshOAuth");
15
+ Object.defineProperty(exports, "OAUTH_MESH_RULESET_RID", { enumerable: true, get: function () { return meshOAuth_1.OAUTH_MESH_RULESET_RID; } });
16
+ Object.defineProperty(exports, "meshRequiresOAuth", { enumerable: true, get: function () { return meshOAuth_1.meshRequiresOAuth; } });
17
+ Object.defineProperty(exports, "rootHasOAuthMeshRuleset", { enumerable: true, get: function () { return meshOAuth_1.rootHasOAuthMeshRuleset; } });
18
+ Object.defineProperty(exports, "rootPicoIdForChannelEci", { enumerable: true, get: function () { return meshOAuth_1.rootPicoIdForChannelEci; } });
19
+ Object.defineProperty(exports, "isChannelUnderRoot", { enumerable: true, get: function () { return meshOAuth_1.isChannelUnderRoot; } });
20
+ var krlModule_1 = require("./krlModule");
21
+ Object.defineProperty(exports, "initOAuthModule", { enumerable: true, get: function () { return krlModule_1.default; } });
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = initOAuthModule;
4
+ const krl_stdlib_1 = require("krl-stdlib");
5
+ function initOAuthModule(oauth) {
6
+ const module = {
7
+ channelStatus: krl_stdlib_1.krl.Function(["eci"], function (eci) {
8
+ return oauth.channelStatusAsync(eci);
9
+ }),
10
+ meshRequiresOAuth: krl_stdlib_1.krl.Function(["eci"], function (eci) {
11
+ return oauth.meshRequiresOAuth(eci);
12
+ }),
13
+ createChannelSecret: krl_stdlib_1.krl.Function(["eci"], function (eci) {
14
+ oauth.assertChannelManagedBy(eci, this.rsCtx.pico().id);
15
+ return oauth.createChannelSecret(eci);
16
+ }),
17
+ revokeChannelSecret: krl_stdlib_1.krl.Function(["eci"], function (eci) {
18
+ oauth.assertChannelManagedBy(eci, this.rsCtx.pico().id);
19
+ return oauth.revokeChannelSecret(eci).then(() => ({ ok: true }));
20
+ }),
21
+ revokeTokens: krl_stdlib_1.krl.Function(["eci"], function (eci) {
22
+ oauth.assertChannelManagedBy(eci, this.rsCtx.pico().id);
23
+ return oauth.revokeTokens(eci).then(() => ({ ok: true }));
24
+ }),
25
+ };
26
+ return module;
27
+ }
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAUTH_MESH_RULESET_RID = void 0;
4
+ exports.rootPicoIdForChannelEci = rootPicoIdForChannelEci;
5
+ exports.meshRequiresOAuth = meshRequiresOAuth;
6
+ exports.rootHasOAuthMeshRuleset = rootHasOAuthMeshRuleset;
7
+ exports.isChannelUnderRoot = isChannelUnderRoot;
8
+ /** Optional ruleset installed on a root pico to enable mesh-level OAuth (Layer 3b). */
9
+ exports.OAUTH_MESH_RULESET_RID = "io.picolabs.oauth";
10
+ function rootPicoIdForChannelEci(pf, eci) {
11
+ try {
12
+ let pico = pf.lookupChannel(eci).pico;
13
+ while (pico.parent) {
14
+ pico = pf.getPico(pico.parent);
15
+ }
16
+ return pico.id;
17
+ }
18
+ catch (_e) {
19
+ return null;
20
+ }
21
+ }
22
+ /** True when the channel's root pico has the mesh OAuth ruleset installed. */
23
+ function meshRequiresOAuth(pf, eci) {
24
+ const rootId = rootPicoIdForChannelEci(pf, eci);
25
+ if (!rootId) {
26
+ return false;
27
+ }
28
+ return rootHasOAuthMeshRuleset(pf, rootId);
29
+ }
30
+ function rootHasOAuthMeshRuleset(pf, rootPicoId) {
31
+ try {
32
+ const root = pf.getPico(rootPicoId);
33
+ return exports.OAUTH_MESH_RULESET_RID in root.rulesets;
34
+ }
35
+ catch (_e) {
36
+ return false;
37
+ }
38
+ }
39
+ /** True when the channel ECI belongs to a pico under rootPicoId (inclusive). */
40
+ function isChannelUnderRoot(pf, channelEci, rootPicoId) {
41
+ const channelRootId = rootPicoIdForChannelEci(pf, channelEci);
42
+ return !!channelRootId && channelRootId === rootPicoId;
43
+ }