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.
- package/README.md +147 -0
- package/dist/auth/AuthService.js +537 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/webauthn.js +97 -0
- package/dist/cli.js +11 -0
- package/dist/index.js +75 -43
- package/dist/oauth/OAuthService.js +356 -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 +80 -0
- package/dist/server.js +558 -15
- package/krl/io.picolabs.oauth.krl +48 -0
- package/krl/io.picolabs.wrangler.krl +4 -4
- package/package.json +14 -8
- package/public/pico-engine-ui.css +1 -1
- package/public/pico-engine-ui.js +21 -20
- package/public/pico-labs-logo.png +0 -0
- package/src/auth/AuthService.ts +755 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/webauthn.ts +182 -0
- package/src/cli.ts +11 -0
- package/src/index.ts +115 -52
- package/src/oauth/OAuthService.ts +474 -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 +97 -0
- package/src/server.ts +643 -24
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.makeWebAuthnAdapter = exports.AuthError = exports.AuthService = void 0;
|
|
4
|
+
var AuthService_1 = require("./AuthService");
|
|
5
|
+
Object.defineProperty(exports, "AuthService", { enumerable: true, get: function () { return AuthService_1.AuthService; } });
|
|
6
|
+
Object.defineProperty(exports, "AuthError", { enumerable: true, get: function () { return AuthService_1.AuthError; } });
|
|
7
|
+
var webauthn_1 = require("./webauthn");
|
|
8
|
+
Object.defineProperty(exports, "makeWebAuthnAdapter", { enumerable: true, get: function () { return webauthn_1.makeWebAuthnAdapter; } });
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.makeWebAuthnAdapter = makeWebAuthnAdapter;
|
|
4
|
+
const server_1 = require("@simplewebauthn/server");
|
|
5
|
+
function makeWebAuthnAdapter() {
|
|
6
|
+
return {
|
|
7
|
+
async generateRegistrationOptions(req) {
|
|
8
|
+
const excludeCredentials = (req.excludeCredentials || []).map((cred) => {
|
|
9
|
+
const id = trimBase64URLPadding(cred.id);
|
|
10
|
+
const transports = (cred.transports || []).filter(Boolean);
|
|
11
|
+
return transports.length > 0 ? { id, transports } : { id };
|
|
12
|
+
});
|
|
13
|
+
return (0, server_1.generateRegistrationOptions)({
|
|
14
|
+
rpName: req.rpName,
|
|
15
|
+
rpID: req.rpID,
|
|
16
|
+
userID: req.userID,
|
|
17
|
+
userName: req.userName,
|
|
18
|
+
userDisplayName: req.userDisplayName,
|
|
19
|
+
attestationType: "none",
|
|
20
|
+
excludeCredentials,
|
|
21
|
+
authenticatorSelection: req.additionalPasskey
|
|
22
|
+
? {
|
|
23
|
+
residentKey: "preferred",
|
|
24
|
+
userVerification: "preferred",
|
|
25
|
+
}
|
|
26
|
+
: {
|
|
27
|
+
residentKey: "required",
|
|
28
|
+
userVerification: "preferred",
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
},
|
|
32
|
+
async verifyRegistration(req) {
|
|
33
|
+
const verification = await (0, server_1.verifyRegistrationResponse)({
|
|
34
|
+
response: req.response,
|
|
35
|
+
expectedChallenge: req.expectedChallenge,
|
|
36
|
+
expectedOrigin: req.expectedOrigin,
|
|
37
|
+
expectedRPID: req.expectedRPID,
|
|
38
|
+
requireUserVerification: false,
|
|
39
|
+
});
|
|
40
|
+
if (!verification.verified || !verification.registrationInfo) {
|
|
41
|
+
return { verified: false };
|
|
42
|
+
}
|
|
43
|
+
const cred = verification.registrationInfo.credential;
|
|
44
|
+
return {
|
|
45
|
+
verified: true,
|
|
46
|
+
credential: {
|
|
47
|
+
id: cred.id,
|
|
48
|
+
publicKey: cred.publicKey,
|
|
49
|
+
counter: cred.counter,
|
|
50
|
+
transports: mergeTransports(cred.transports, req.response),
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
},
|
|
54
|
+
async generateAuthenticationOptions(req) {
|
|
55
|
+
return (0, server_1.generateAuthenticationOptions)({
|
|
56
|
+
rpID: req.rpID,
|
|
57
|
+
userVerification: "preferred",
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
async verifyAuthentication(req) {
|
|
61
|
+
var _a, _b;
|
|
62
|
+
const verification = await (0, server_1.verifyAuthenticationResponse)({
|
|
63
|
+
response: req.response,
|
|
64
|
+
expectedChallenge: req.expectedChallenge,
|
|
65
|
+
expectedOrigin: req.expectedOrigin,
|
|
66
|
+
expectedRPID: req.expectedRPID,
|
|
67
|
+
credential: {
|
|
68
|
+
id: req.credential.id,
|
|
69
|
+
publicKey: req.credential.publicKey,
|
|
70
|
+
counter: req.credential.counter,
|
|
71
|
+
transports: req.credential.transports,
|
|
72
|
+
},
|
|
73
|
+
requireUserVerification: false,
|
|
74
|
+
});
|
|
75
|
+
return {
|
|
76
|
+
verified: verification.verified,
|
|
77
|
+
newCounter: (_b = (_a = verification.authenticationInfo) === null || _a === void 0 ? void 0 : _a.newCounter) !== null && _b !== void 0 ? _b : req.credential.counter,
|
|
78
|
+
};
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function trimBase64URLPadding(id) {
|
|
83
|
+
return id.replace(/=+$/g, "");
|
|
84
|
+
}
|
|
85
|
+
function mergeTransports(fromAttestation, response) {
|
|
86
|
+
const merged = [...(fromAttestation || [])].filter(Boolean);
|
|
87
|
+
if (merged.length > 0) {
|
|
88
|
+
return merged;
|
|
89
|
+
}
|
|
90
|
+
if (response.authenticatorAttachment === "platform") {
|
|
91
|
+
return ["internal"];
|
|
92
|
+
}
|
|
93
|
+
if (response.authenticatorAttachment === "cross-platform") {
|
|
94
|
+
return ["usb", "ble", "nfc"];
|
|
95
|
+
}
|
|
96
|
+
return [];
|
|
97
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -23,6 +23,10 @@ Environment Variables:
|
|
|
23
23
|
PORT - The port the http server should listen on. By default it's 3000
|
|
24
24
|
PICO_ENGINE_HOME - Where the database and other files should be stored. By default it's ~/.pico-engine/
|
|
25
25
|
PICO_ENGINE_BASE_URL - The public url prefix to reach this engine. By default it's http://localhost:$PORT
|
|
26
|
+
PICO_ENGINE_ALLOW_SELF_SIGNUP - Set to "true" or "1" to allow anyone to register a new account
|
|
27
|
+
after the engine is bootstrapped. Default is false (login only; bootstrap and invite still work).
|
|
28
|
+
PICO_ENGINE_ALLOW_LOCALHOST_C - Set to "0" to require passkey session on /c/* even from localhost.
|
|
29
|
+
Default (unset) allows localhost without session for in-engine ctx:event HTTP loops. See MEMORY.md.
|
|
26
30
|
`);
|
|
27
31
|
process.exit(0);
|
|
28
32
|
}
|
|
@@ -41,6 +45,13 @@ if (typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
|
|
|
41
45
|
process.env.PICO_ENGINE_BASE_URL.length > 0) {
|
|
42
46
|
env.base_url = process.env.PICO_ENGINE_BASE_URL;
|
|
43
47
|
}
|
|
48
|
+
const allowSelfSignupEnv = process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP;
|
|
49
|
+
if (allowSelfSignupEnv === "true" || allowSelfSignupEnv === "1") {
|
|
50
|
+
env.allowSelfSignup = true;
|
|
51
|
+
}
|
|
52
|
+
else if (allowSelfSignupEnv === "false" || allowSelfSignupEnv === "0") {
|
|
53
|
+
env.allowSelfSignup = false;
|
|
54
|
+
}
|
|
44
55
|
(0, index_1.startEngine)(env).catch((err) => {
|
|
45
56
|
console.error("Failed to start engine.");
|
|
46
57
|
console.error(err);
|
package/dist/index.js
CHANGED
|
@@ -7,20 +7,31 @@ const _ = require("lodash");
|
|
|
7
7
|
const makeDir = require("make-dir");
|
|
8
8
|
const path = require("path");
|
|
9
9
|
const pico_engine_core_1 = require("pico-engine-core");
|
|
10
|
+
const auth_1 = require("./auth");
|
|
11
|
+
const oauth_1 = require("./oauth");
|
|
10
12
|
const logging_1 = require("./logging");
|
|
13
|
+
const provisionRoot_1 = require("./provisionRoot");
|
|
11
14
|
const RulesetRegistryLoaderFs_1 = require("./RulesetRegistryLoaderFs");
|
|
12
15
|
const server_1 = require("./server");
|
|
13
|
-
const toFileUrl_1 = require("./utils/toFileUrl");
|
|
14
16
|
const charwise = require("charwise");
|
|
15
17
|
const safeJsonCodec = require("level-json-coerce-null");
|
|
16
18
|
const homeDir = require("home-dir");
|
|
17
19
|
const version = require("../package.json").version;
|
|
18
20
|
async function startEngine(configuration = {}) {
|
|
21
|
+
var _a, _b;
|
|
19
22
|
let home = configuration.home;
|
|
20
23
|
let port = configuration.port;
|
|
21
24
|
let base_url = configuration.base_url;
|
|
22
25
|
if (typeof home !== "string") {
|
|
23
|
-
|
|
26
|
+
const envHome = process.env.PICO_ENGINE_HOME;
|
|
27
|
+
if (typeof envHome === "string" &&
|
|
28
|
+
envHome.length > 0 &&
|
|
29
|
+
process.env.NODE_ENV === "test") {
|
|
30
|
+
home = envHome;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
home = homeDir(".pico-engine");
|
|
34
|
+
}
|
|
24
35
|
}
|
|
25
36
|
await makeDir(home);
|
|
26
37
|
const logFilePath = path.resolve(home, "pico-engine.log");
|
|
@@ -36,6 +47,7 @@ async function startEngine(configuration = {}) {
|
|
|
36
47
|
log,
|
|
37
48
|
modules: configuration.modules,
|
|
38
49
|
useEventInputTime: configuration.useEventInputTime,
|
|
50
|
+
autoCreateRootPico: (_a = configuration.autoCreateRootPico) !== null && _a !== void 0 ? _a : false,
|
|
39
51
|
getPicoLogs(picoId) {
|
|
40
52
|
return (0, logging_1.getPicoLogs)(logFilePath, picoId);
|
|
41
53
|
},
|
|
@@ -43,40 +55,57 @@ async function startEngine(configuration = {}) {
|
|
|
43
55
|
await core.start();
|
|
44
56
|
const rsRegistry = core.rsRegistry;
|
|
45
57
|
const pf = core.picoFramework;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
(0,
|
|
52
|
-
|
|
53
|
-
for (const url of krl_urls) {
|
|
54
|
-
const { ruleset } = await rsRegistry.flush(url);
|
|
55
|
-
await pf.rootPico.install(ruleset, { url, config: {} });
|
|
58
|
+
// Fresh engines boot with zero roots. Adopt + (re)provision only when roots
|
|
59
|
+
// already exist (test harness with autoCreateRootPico, or a migrated DB).
|
|
60
|
+
let uiECI = null;
|
|
61
|
+
const existingRoots = pf.rootPicos();
|
|
62
|
+
if (existingRoots.length > 0) {
|
|
63
|
+
const provisioned = await (0, provisionRoot_1.provisionRoot)(pf, core, { root: existingRoots[0] });
|
|
64
|
+
uiECI = provisioned.uiECI;
|
|
56
65
|
}
|
|
57
|
-
|
|
58
|
-
.
|
|
59
|
-
.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
},
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
66
|
+
const auth = new auth_1.AuthService({
|
|
67
|
+
db: pf.db,
|
|
68
|
+
webauthn: configuration.webauthn || (0, auth_1.makeWebAuthnAdapter)(),
|
|
69
|
+
getBaseUrl: () => core.base_url,
|
|
70
|
+
rpID: configuration.rpID,
|
|
71
|
+
rpName: configuration.rpName,
|
|
72
|
+
origin: configuration.origin,
|
|
73
|
+
allowSelfSignup: (_b = configuration.allowSelfSignup) !== null && _b !== void 0 ? _b : false,
|
|
74
|
+
provisionRoot: async (opts) => {
|
|
75
|
+
const { root, uiECI } = await (0, provisionRoot_1.provisionRoot)(pf, core, opts);
|
|
76
|
+
return { rootPicoId: root.id, uiECI };
|
|
77
|
+
},
|
|
78
|
+
getUiECI: (rootPicoId) => (0, provisionRoot_1.uiECIForRoot)(pf, rootPicoId),
|
|
79
|
+
getPrimaryRootPicoId: () => {
|
|
80
|
+
try {
|
|
81
|
+
return pf.rootPico.id;
|
|
82
|
+
}
|
|
83
|
+
catch (_a) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
onAccountClaimed: async (rootPicoId, displayName) => {
|
|
88
|
+
const uiChannel = (0, provisionRoot_1.uiECIForRoot)(pf, rootPicoId);
|
|
89
|
+
if (!uiChannel || !displayName.trim()) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
await pf.eventWait({
|
|
93
|
+
eci: uiChannel,
|
|
94
|
+
domain: "engine_ui",
|
|
95
|
+
name: "box",
|
|
96
|
+
data: { attrs: { name: displayName.trim() } },
|
|
97
|
+
time: 0,
|
|
98
|
+
});
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
const oauth = new oauth_1.OAuthService({
|
|
102
|
+
db: pf.db,
|
|
103
|
+
pf,
|
|
75
104
|
});
|
|
76
|
-
|
|
77
|
-
const app = (0, server_1.server)(core, uiECI);
|
|
105
|
+
core.modules["oauth"] = (0, oauth_1.initOAuthModule)(oauth);
|
|
106
|
+
const app = (0, server_1.server)(core, uiECI, auth, oauth);
|
|
78
107
|
if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
|
|
79
|
-
port = 3000;
|
|
108
|
+
port = process.env.NODE_ENV === "test" ? 0 : 3000;
|
|
80
109
|
}
|
|
81
110
|
await new Promise((resolve) => {
|
|
82
111
|
const listener = app.listen(port, () => {
|
|
@@ -95,16 +124,17 @@ async function startEngine(configuration = {}) {
|
|
|
95
124
|
}
|
|
96
125
|
core.base_url = base_url;
|
|
97
126
|
log.info(`Listening at ${base_url}`);
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
127
|
+
if (uiECI) {
|
|
128
|
+
pf.event({
|
|
129
|
+
eci: uiECI,
|
|
130
|
+
domain: "engine",
|
|
131
|
+
name: "started",
|
|
132
|
+
data: { attrs: {} },
|
|
133
|
+
time: 0, // TODO remove this typescript requirement
|
|
134
|
+
}).catch((error) => {
|
|
135
|
+
log.error("Error signaling engine:started event", { error });
|
|
136
|
+
});
|
|
137
|
+
}
|
|
108
138
|
return {
|
|
109
139
|
version,
|
|
110
140
|
home,
|
|
@@ -113,5 +143,7 @@ async function startEngine(configuration = {}) {
|
|
|
113
143
|
pf,
|
|
114
144
|
uiECI,
|
|
115
145
|
rsRegistry,
|
|
146
|
+
auth,
|
|
147
|
+
oauth,
|
|
116
148
|
};
|
|
117
149
|
}
|
|
@@ -0,0 +1,356 @@
|
|
|
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.OAuthService = exports.renderConsentHtml = exports.parseApproveBody = exports.parseAuthorizeQuery = exports.DEFAULT_ACG_SCOPE = exports.OAuthError = exports.MAX_TOKEN_TTL_SEC = exports.MIN_TOKEN_TTL_SEC = void 0;
|
|
11
|
+
const crypto = require("crypto");
|
|
12
|
+
const acg = require("./acg");
|
|
13
|
+
const channelEligibility_1 = require("./channelEligibility");
|
|
14
|
+
const errors_1 = require("./errors");
|
|
15
|
+
const meshOAuth_1 = require("./meshOAuth");
|
|
16
|
+
const OAUTH_CHANNEL_PREFIX = "oauth-channel";
|
|
17
|
+
const OAUTH_TOKEN_PREFIX = "oauth-token";
|
|
18
|
+
const DEFAULT_TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
19
|
+
exports.MIN_TOKEN_TTL_SEC = 5 * 60; // 5 minutes
|
|
20
|
+
exports.MAX_TOKEN_TTL_SEC = 90 * 24 * 60 * 60; // 90 days
|
|
21
|
+
var errors_2 = require("./errors");
|
|
22
|
+
Object.defineProperty(exports, "OAuthError", { enumerable: true, get: function () { return errors_2.OAuthError; } });
|
|
23
|
+
var acg_1 = require("./acg");
|
|
24
|
+
Object.defineProperty(exports, "DEFAULT_ACG_SCOPE", { enumerable: true, get: function () { return acg_1.DEFAULT_ACG_SCOPE; } });
|
|
25
|
+
Object.defineProperty(exports, "parseAuthorizeQuery", { enumerable: true, get: function () { return acg_1.parseAuthorizeQuery; } });
|
|
26
|
+
Object.defineProperty(exports, "parseApproveBody", { enumerable: true, get: function () { return acg_1.parseApproveBody; } });
|
|
27
|
+
Object.defineProperty(exports, "renderConsentHtml", { enumerable: true, get: function () { return acg_1.renderConsentHtml; } });
|
|
28
|
+
class OAuthService {
|
|
29
|
+
constructor(deps) {
|
|
30
|
+
this.deps = deps;
|
|
31
|
+
}
|
|
32
|
+
get tokenTtlMs() {
|
|
33
|
+
var _a;
|
|
34
|
+
return (_a = this.deps.tokenTtlMs) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_TTL_MS;
|
|
35
|
+
}
|
|
36
|
+
lookupChannelReadOnly(eci) {
|
|
37
|
+
return this.deps.pf.lookupChannel(eci).toReadOnly();
|
|
38
|
+
}
|
|
39
|
+
channelStatus(eci) {
|
|
40
|
+
let channel;
|
|
41
|
+
try {
|
|
42
|
+
channel = this.lookupChannelReadOnly(eci);
|
|
43
|
+
}
|
|
44
|
+
catch (_e) {
|
|
45
|
+
return { eligible: false, enabled: false, hasSecret: false, reason: "Channel not found" };
|
|
46
|
+
}
|
|
47
|
+
if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
|
|
48
|
+
return {
|
|
49
|
+
eligible: false,
|
|
50
|
+
enabled: false,
|
|
51
|
+
hasSecret: false,
|
|
52
|
+
reason: "Channel is not eligible for OAuth webhooks",
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
eligible: true,
|
|
57
|
+
enabled: true,
|
|
58
|
+
clientId: eci,
|
|
59
|
+
hasSecret: false,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
async channelRequiresBearer(eci) {
|
|
63
|
+
try {
|
|
64
|
+
return (0, channelEligibility_1.isOAuthEligibleChannel)(this.lookupChannelReadOnly(eci));
|
|
65
|
+
}
|
|
66
|
+
catch (_e) {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
meshRequiresOAuth(eci) {
|
|
71
|
+
return (0, meshOAuth_1.meshRequiresOAuth)(this.deps.pf, eci);
|
|
72
|
+
}
|
|
73
|
+
/** @deprecated use channelRequiresBearer */
|
|
74
|
+
async channelOAuthEnabled(eci) {
|
|
75
|
+
return this.channelRequiresBearer(eci);
|
|
76
|
+
}
|
|
77
|
+
async channelStatusAsync(eci) {
|
|
78
|
+
let channel;
|
|
79
|
+
try {
|
|
80
|
+
channel = this.lookupChannelReadOnly(eci);
|
|
81
|
+
}
|
|
82
|
+
catch (_e) {
|
|
83
|
+
return { eligible: false, enabled: false, hasSecret: false, reason: "Channel not found" };
|
|
84
|
+
}
|
|
85
|
+
if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
|
|
86
|
+
return {
|
|
87
|
+
eligible: false,
|
|
88
|
+
enabled: false,
|
|
89
|
+
hasSecret: false,
|
|
90
|
+
reason: "Channel is not eligible for OAuth webhooks",
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const stored = await this.getChannelOAuth(eci);
|
|
94
|
+
const hasSecret = !!stored;
|
|
95
|
+
return {
|
|
96
|
+
eligible: true,
|
|
97
|
+
enabled: true,
|
|
98
|
+
clientId: eci,
|
|
99
|
+
hasSecret,
|
|
100
|
+
createdAt: stored === null || stored === void 0 ? void 0 : stored.createdAt,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
async createChannelSecret(eci) {
|
|
104
|
+
const channel = this.assertEligibleChannel(eci);
|
|
105
|
+
const rootPicoId = this.rootPicoIdForChannel(channel);
|
|
106
|
+
const client_secret = randomSecret();
|
|
107
|
+
const secretSalt = randomSalt();
|
|
108
|
+
const record = {
|
|
109
|
+
channelEci: eci,
|
|
110
|
+
rootPicoId,
|
|
111
|
+
secretSalt,
|
|
112
|
+
secretHash: hashSecret(client_secret, secretSalt),
|
|
113
|
+
createdAt: new Date().toISOString(),
|
|
114
|
+
};
|
|
115
|
+
await this.deps.db.put([OAUTH_CHANNEL_PREFIX, eci], record);
|
|
116
|
+
await this.revokeTokens(eci);
|
|
117
|
+
return { client_id: eci, client_secret };
|
|
118
|
+
}
|
|
119
|
+
async revokeChannelSecret(eci) {
|
|
120
|
+
this.assertEligibleChannel(eci);
|
|
121
|
+
await this.deps.db.del([OAUTH_CHANNEL_PREFIX, eci]);
|
|
122
|
+
await this.revokeTokens(eci);
|
|
123
|
+
}
|
|
124
|
+
async revokeTokens(eci) {
|
|
125
|
+
const rows = await dbList(this.deps.db, [OAUTH_TOKEN_PREFIX]);
|
|
126
|
+
for (const row of rows) {
|
|
127
|
+
if (row.value.channelEci === eci) {
|
|
128
|
+
await this.deps.db.del(row.key);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async clientCredentialsGrant(input) {
|
|
133
|
+
const client_id = (input.client_id || "").trim();
|
|
134
|
+
const client_secret = (input.client_secret || "").trim();
|
|
135
|
+
if (client_id.startsWith("app_")) {
|
|
136
|
+
throw new errors_1.OAuthError("OAuth apps require grant_type=authorization_code or refresh_token, not client_credentials", "invalid_client", 401);
|
|
137
|
+
}
|
|
138
|
+
if (!client_id || !client_secret) {
|
|
139
|
+
throw new errors_1.OAuthError("Missing client credentials", "invalid_client", 401);
|
|
140
|
+
}
|
|
141
|
+
const channel = this.assertEligibleChannel(client_id);
|
|
142
|
+
const stored = await this.getChannelOAuth(client_id);
|
|
143
|
+
if (!stored) {
|
|
144
|
+
throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
|
|
145
|
+
}
|
|
146
|
+
if (!verifySecret(client_secret, stored.secretSalt, stored.secretHash)) {
|
|
147
|
+
throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
|
|
148
|
+
}
|
|
149
|
+
const tokenTtlMs = resolveTokenTtlMs(input.expires_in, this.tokenTtlMs);
|
|
150
|
+
const token = acg.mintAccessToken();
|
|
151
|
+
const expiresAt = tokenTtlMs === null ? 0 : Date.now() + tokenTtlMs;
|
|
152
|
+
const tokenRecord = {
|
|
153
|
+
token,
|
|
154
|
+
grant: "client_credentials",
|
|
155
|
+
channelEci: client_id,
|
|
156
|
+
rootPicoId: stored.rootPicoId,
|
|
157
|
+
expiresAt,
|
|
158
|
+
createdAt: new Date().toISOString(),
|
|
159
|
+
};
|
|
160
|
+
await this.deps.db.put([OAUTH_TOKEN_PREFIX, token], tokenRecord);
|
|
161
|
+
const response = {
|
|
162
|
+
access_token: token,
|
|
163
|
+
token_type: "Bearer",
|
|
164
|
+
};
|
|
165
|
+
if (tokenTtlMs !== null) {
|
|
166
|
+
response.expires_in = Math.floor(tokenTtlMs / 1000);
|
|
167
|
+
}
|
|
168
|
+
return response;
|
|
169
|
+
}
|
|
170
|
+
async skyRequiresBearer(eci) {
|
|
171
|
+
if (await this.channelRequiresBearer(eci)) {
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
return this.meshRequiresOAuth(eci);
|
|
175
|
+
}
|
|
176
|
+
async validateBearerToken(token, channelEci) {
|
|
177
|
+
return this.validateSkyBearerToken(token, channelEci);
|
|
178
|
+
}
|
|
179
|
+
async validateSkyBearerToken(token, channelEci) {
|
|
180
|
+
const trimmed = (token || "").trim();
|
|
181
|
+
if (!trimmed || !channelEci) {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
const record = await this.getTokenRecord(trimmed);
|
|
185
|
+
if (!record) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
if (record.expiresAt !== 0 && record.expiresAt < Date.now()) {
|
|
189
|
+
await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
const grant = record.grant || "client_credentials";
|
|
193
|
+
if (grant === "authorization_code") {
|
|
194
|
+
return (0, meshOAuth_1.isChannelUnderRoot)(this.deps.pf, channelEci, record.rootPicoId);
|
|
195
|
+
}
|
|
196
|
+
return record.channelEci === channelEci;
|
|
197
|
+
}
|
|
198
|
+
listApps(rootPicoId) {
|
|
199
|
+
return acg.listApps(this.acgContext(), rootPicoId);
|
|
200
|
+
}
|
|
201
|
+
registerApp(rootPicoId, input) {
|
|
202
|
+
return acg.registerApp(this.acgContext(), rootPicoId, input);
|
|
203
|
+
}
|
|
204
|
+
revokeApp(rootPicoId, clientId) {
|
|
205
|
+
return acg.revokeApp(this.acgContext(), rootPicoId, clientId);
|
|
206
|
+
}
|
|
207
|
+
getAppForAuthorize(params) {
|
|
208
|
+
return acg.getAppForAuthorize(this.acgContext(), params);
|
|
209
|
+
}
|
|
210
|
+
approveAuthorization(session, params) {
|
|
211
|
+
return acg.approveAuthorization(this.acgContext(), session, params);
|
|
212
|
+
}
|
|
213
|
+
authorizationCodeGrant(input) {
|
|
214
|
+
return acg.authorizationCodeGrant(this.acgContext(), input);
|
|
215
|
+
}
|
|
216
|
+
refreshTokenGrant(input) {
|
|
217
|
+
return acg.refreshTokenGrant(this.acgContext(), input);
|
|
218
|
+
}
|
|
219
|
+
tokenGrant(body) {
|
|
220
|
+
const grant_type = String(body.grant_type || "client_credentials").trim();
|
|
221
|
+
if (grant_type === "authorization_code") {
|
|
222
|
+
return this.authorizationCodeGrant(body);
|
|
223
|
+
}
|
|
224
|
+
if (grant_type === "refresh_token") {
|
|
225
|
+
return this.refreshTokenGrant(body);
|
|
226
|
+
}
|
|
227
|
+
return this.clientCredentialsGrant(body);
|
|
228
|
+
}
|
|
229
|
+
acgContext() {
|
|
230
|
+
return {
|
|
231
|
+
db: this.deps.db,
|
|
232
|
+
pf: this.deps.pf,
|
|
233
|
+
tokenTtlMs: this.tokenTtlMs,
|
|
234
|
+
putAccessToken: async (record) => {
|
|
235
|
+
const tokenRecord = {
|
|
236
|
+
token: record.token,
|
|
237
|
+
grant: "authorization_code",
|
|
238
|
+
rootPicoId: record.rootPicoId,
|
|
239
|
+
appId: record.appId,
|
|
240
|
+
accountId: record.accountId,
|
|
241
|
+
scope: record.scope,
|
|
242
|
+
expiresAt: record.expiresAt,
|
|
243
|
+
createdAt: new Date().toISOString(),
|
|
244
|
+
};
|
|
245
|
+
await this.deps.db.put([OAUTH_TOKEN_PREFIX, record.token], tokenRecord);
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
async getTokenRecord(token) {
|
|
250
|
+
return dbGet(this.deps.db, [OAUTH_TOKEN_PREFIX, token]);
|
|
251
|
+
}
|
|
252
|
+
/** Channel owner or an ancestor pico in the admin tree may manage webhook OAuth. */
|
|
253
|
+
assertChannelManagedBy(eci, callerPicoId) {
|
|
254
|
+
const channel = this.lookupChannelReadOnly(eci);
|
|
255
|
+
let pico = this.deps.pf.lookupChannel(eci).pico;
|
|
256
|
+
while (true) {
|
|
257
|
+
if (pico.id === callerPicoId) {
|
|
258
|
+
return channel;
|
|
259
|
+
}
|
|
260
|
+
if (!pico.parent) {
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
pico = this.deps.pf.getPico(pico.parent);
|
|
264
|
+
}
|
|
265
|
+
throw new errors_1.OAuthError("Channel is not in this pico's subtree", "invalid_request", 403);
|
|
266
|
+
}
|
|
267
|
+
assertEligibleChannel(eci) {
|
|
268
|
+
const channel = this.lookupChannelReadOnly(eci);
|
|
269
|
+
if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
|
|
270
|
+
throw new errors_1.OAuthError("Channel is not eligible for OAuth webhooks", "invalid_client", 403);
|
|
271
|
+
}
|
|
272
|
+
return channel;
|
|
273
|
+
}
|
|
274
|
+
rootPicoIdForChannel(channel) {
|
|
275
|
+
const owner = this.deps.pf.lookupChannel(channel.id).pico;
|
|
276
|
+
let pico = owner;
|
|
277
|
+
while (pico.parent) {
|
|
278
|
+
pico = this.deps.pf.getPico(pico.parent);
|
|
279
|
+
}
|
|
280
|
+
return pico.id;
|
|
281
|
+
}
|
|
282
|
+
async getChannelOAuth(eci) {
|
|
283
|
+
return dbGet(this.deps.db, [OAUTH_CHANNEL_PREFIX, eci]);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
exports.OAuthService = OAuthService;
|
|
287
|
+
async function dbGet(db, key) {
|
|
288
|
+
try {
|
|
289
|
+
const value = await db.get(key);
|
|
290
|
+
return value === undefined ? null : value;
|
|
291
|
+
}
|
|
292
|
+
catch (err) {
|
|
293
|
+
if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
throw err;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async function dbList(db, prefix) {
|
|
300
|
+
var _a, e_1, _b, _c;
|
|
301
|
+
const out = [];
|
|
302
|
+
const iter = db.iterator({
|
|
303
|
+
gte: prefix,
|
|
304
|
+
lte: prefix.concat([undefined]),
|
|
305
|
+
});
|
|
306
|
+
try {
|
|
307
|
+
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) {
|
|
308
|
+
_c = iter_1_1.value;
|
|
309
|
+
_d = false;
|
|
310
|
+
const [key, value] = _c;
|
|
311
|
+
out.push({ key, value });
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
315
|
+
finally {
|
|
316
|
+
try {
|
|
317
|
+
if (!_d && !_a && (_b = iter_1.return)) await _b.call(iter_1);
|
|
318
|
+
}
|
|
319
|
+
finally { if (e_1) throw e_1.error; }
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
function resolveTokenTtlMs(expires_in, defaultMs) {
|
|
324
|
+
if (expires_in === undefined || expires_in === null || expires_in === "") {
|
|
325
|
+
return defaultMs;
|
|
326
|
+
}
|
|
327
|
+
if (typeof expires_in === "string" && expires_in.trim().toLowerCase() === "never") {
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
const seconds = typeof expires_in === "string" ? Number.parseInt(expires_in, 10) : expires_in;
|
|
331
|
+
if (seconds === 0) {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
if (!Number.isFinite(seconds) ||
|
|
335
|
+
seconds < exports.MIN_TOKEN_TTL_SEC ||
|
|
336
|
+
seconds > exports.MAX_TOKEN_TTL_SEC) {
|
|
337
|
+
throw new errors_1.OAuthError(`expires_in must be 0 (never), or between ${exports.MIN_TOKEN_TTL_SEC} and ${exports.MAX_TOKEN_TTL_SEC} seconds`, "invalid_request", 400);
|
|
338
|
+
}
|
|
339
|
+
return seconds * 1000;
|
|
340
|
+
}
|
|
341
|
+
function randomSecret() {
|
|
342
|
+
return crypto.randomBytes(32).toString("base64url");
|
|
343
|
+
}
|
|
344
|
+
function randomSalt() {
|
|
345
|
+
return crypto.randomBytes(16).toString("base64url");
|
|
346
|
+
}
|
|
347
|
+
function hashSecret(secret, salt) {
|
|
348
|
+
return crypto.createHash("sha256").update(salt + secret).digest("base64url");
|
|
349
|
+
}
|
|
350
|
+
function verifySecret(secret, salt, expected) {
|
|
351
|
+
const actual = hashSecret(secret, salt);
|
|
352
|
+
if (actual.length !== expected.length) {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
return crypto.timingSafeEqual(Buffer.from(actual), Buffer.from(expected));
|
|
356
|
+
}
|