jso-protector 0.2.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/CHANGELOG.md +960 -0
- package/LICENSE +90 -0
- package/MIGRATION.md +207 -0
- package/README.md +1477 -0
- package/RELEASE.md +82 -0
- package/SECURITY.md +71 -0
- package/ai-cli.js +392 -0
- package/ai.js +176 -0
- package/bin/jso-protector.js +12066 -0
- package/browserify.d.ts +10 -0
- package/browserify.js +88 -0
- package/bun.d.ts +10 -0
- package/bun.js +41 -0
- package/ci/Jenkinsfile +82 -0
- package/ci/argo-workflows.yaml +121 -0
- package/ci/azure-pipelines.yml +56 -0
- package/ci/bitbucket-pipelines.yml +43 -0
- package/ci/buildkite.yml +50 -0
- package/ci/circleci.yml +60 -0
- package/ci/drone.yml +67 -0
- package/ci/github-actions.yml +51 -0
- package/ci/gitlab-ci.yml +39 -0
- package/ci/gocd.yaml +79 -0
- package/ci/teamcity.kts +79 -0
- package/ci/tekton.yaml +106 -0
- package/ci/verify-package.js +748 -0
- package/ci/verify-publish-metadata.js +147 -0
- package/ci/verify-templates.js +195 -0
- package/ci/woodpecker.yml +53 -0
- package/compliance/cli.js +204 -0
- package/compliance/evidence-forwarder.js +209 -0
- package/compliance/pci-dss-v4/controls.json +75 -0
- package/compliance/pci-dss-v4/index.js +2613 -0
- package/config/named-sets.js +185 -0
- package/esbuild.d.ts +16 -0
- package/esbuild.js +190 -0
- package/examples/README.md +78 -0
- package/examples/browserify/build.js +20 -0
- package/examples/bun/package.json +13 -0
- package/examples/bun/scripts/protect-release.js +28 -0
- package/examples/cli-basic/jso.config.cjs +23 -0
- package/examples/cli-basic/jso.config.json +15 -0
- package/examples/cli-basic/package.json +14 -0
- package/examples/cli-basic/scripts/build.js +10 -0
- package/examples/curl/README.md +55 -0
- package/examples/curl/protect.sh +106 -0
- package/examples/esbuild/build.js +19 -0
- package/examples/grunt/Gruntfile.js +29 -0
- package/examples/gulp/gulpfile.js +19 -0
- package/examples/helm/Chart.yaml +27 -0
- package/examples/helm/README.md +69 -0
- package/examples/helm/templates/_helpers.tpl +23 -0
- package/examples/helm/templates/_podtemplate.tpl +64 -0
- package/examples/helm/templates/job.yaml +39 -0
- package/examples/helm/templates/secret.yaml +17 -0
- package/examples/helm/values.yaml +54 -0
- package/examples/kubernetes/job.yaml +123 -0
- package/examples/metro.config.js +11 -0
- package/examples/nextjs/next.config.js +11 -0
- package/examples/node-api/protect-release.js +28 -0
- package/examples/node-api/release-summary.js +59 -0
- package/examples/parcel/package.json +13 -0
- package/examples/parcel/scripts/protect-release.js +28 -0
- package/examples/payment-page-script-inventory.json +62 -0
- package/examples/payment-page-security-headers.json +46 -0
- package/examples/pre-commit/.pre-commit-config.yaml +33 -0
- package/examples/pre-commit/README.md +45 -0
- package/examples/react-native/README.md +208 -0
- package/examples/react-native/metro.config.js +11 -0
- package/examples/rollup/rollup.config.js +20 -0
- package/examples/rspack/rspack.config.js +28 -0
- package/examples/turbopack/package.json +13 -0
- package/examples/turbopack/scripts/protect-release.js +28 -0
- package/examples/vite/vite.config.js +18 -0
- package/examples/webpack/webpack.config.js +21 -0
- package/examples/webpack-loader/webpack.config.js +22 -0
- package/governance/index.d.ts +18 -0
- package/governance/index.js +309 -0
- package/grunt.d.ts +4 -0
- package/grunt.js +111 -0
- package/gulp.d.ts +10 -0
- package/gulp.js +106 -0
- package/index.d.ts +879 -0
- package/index.js +607 -0
- package/jso.config.example.json +29 -0
- package/jso.config.schema.json +548 -0
- package/metro.d.ts +43 -0
- package/metro.js +117 -0
- package/next.d.ts +24 -0
- package/next.js +64 -0
- package/package.json +241 -0
- package/parcel.d.ts +10 -0
- package/parcel.js +40 -0
- package/react-native.d.ts +2 -0
- package/react-native.js +3 -0
- package/release-signer.js +245 -0
- package/rollup.d.ts +13 -0
- package/rollup.js +71 -0
- package/rspack-loader.d.ts +13 -0
- package/rspack-loader.js +11 -0
- package/rspack.d.ts +11 -0
- package/rspack.js +9 -0
- package/runtime/ai-script-governance.js +379 -0
- package/runtime/countermeasures.js +0 -0
- package/runtime/data-exfiltration-guard.d.ts +7 -0
- package/runtime/data-exfiltration-guard.js +161 -0
- package/runtime/environment-integrity.js +389 -0
- package/runtime/managed-integrity.d.ts +4 -0
- package/runtime/managed-integrity.js +108 -0
- package/runtime/third-party-inventory.js +437 -0
- package/turbopack.d.ts +10 -0
- package/turbopack.js +41 -0
- package/vite.d.ts +16 -0
- package/vite.js +78 -0
- package/watermark.js +126 -0
- package/webpack-loader.d.ts +15 -0
- package/webpack-loader.js +97 -0
- package/webpack.d.ts +13 -0
- package/webpack.js +143 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type GovernanceRole = "owner" | "admin" | "developer" | "reviewer" | "viewer";
|
|
2
|
+
export type GovernanceAction = "protect" | "view_evidence" | "export_evidence" | "manage_projects" | "manage_members" | "manage_tokens" | "manage_billing" | "view_audit";
|
|
3
|
+
export type TokenScope = "protect" | "evidence:read" | "evidence:export" | "projects:write" | "audit:read";
|
|
4
|
+
export interface GovernanceMember { id: string; role: GovernanceRole; active?: boolean; }
|
|
5
|
+
export interface AuthorizationResult { allowed: boolean; reason: string; role?: GovernanceRole; }
|
|
6
|
+
export interface TokenDescriptor { id: string; name: string; createdBy: string; scopes: TokenScope[]; expiresAt: string | null; revokedAt: string | null; }
|
|
7
|
+
export declare const ROLE_PERMISSIONS: Readonly<Record<GovernanceRole, readonly GovernanceAction[]>>;
|
|
8
|
+
export declare const TOKEN_SCOPES: readonly TokenScope[];
|
|
9
|
+
export declare function createGovernancePolicy(config: { members: GovernanceMember[] }): { authorize(actorId: string, action: GovernanceAction): AuthorizationResult; describe(): object; };
|
|
10
|
+
export declare function createTokenDescriptor(input: { id: string; name?: string; createdBy: string; scopes?: TokenScope[]; expiresAt?: string | Date; revokedAt?: string | Date }): TokenDescriptor;
|
|
11
|
+
export declare function authorizeToken(token: TokenDescriptor, scope: TokenScope, now?: string | Date): AuthorizationResult;
|
|
12
|
+
export declare function createAuditTrail(config: { organizationId: string }): { append(event: { actorId: string; action: string; target?: string; outcome?: string; occurredAt?: string | Date; metadata?: Record<string, unknown> }): object; verify(rows?: object[]): boolean; events(): object[]; };
|
|
13
|
+
export interface EnterpriseIdentityConfig { protocol: "oidc" | "saml"; domains: readonly string[]; issuer: string | null; clientId: string | null; ssoUrl: string | null; entityId: string | null; certificateFingerprint: string | null; enforceSso: boolean; defaultRole: GovernanceRole; }
|
|
14
|
+
export interface ScimUser { schemas: readonly string[]; id: string; userName: string; displayName: string; role: GovernanceRole; active: boolean; organizationId: string; externalId: string | null; meta: { resourceType: "User"; version: string }; }
|
|
15
|
+
export declare function validateEnterpriseIdentityConfig(input: { protocol: "oidc" | "saml"; domains: string[]; issuer?: string; clientId?: string; ssoUrl?: string; entityId?: string; certificate?: string; enforceSso?: boolean; defaultRole?: GovernanceRole }): EnterpriseIdentityConfig;
|
|
16
|
+
export declare function authenticateEnterprisePrincipal(config: EnterpriseIdentityConfig, assertion: Record<string, unknown>, context: { signatureVerified: true; now?: string | Date; nonce?: string; audience?: string }): { subject: string; email: string; domain: string; role: GovernanceRole; protocol: "oidc" | "saml"; };
|
|
17
|
+
export declare function createOrganizationDirectory(config: { organizationId: string; users?: Partial<ScimUser>[] }): { organizationId: string; upsertUser(input: Partial<ScimUser> & { id?: string; userName: string }): ScimUser; patchUser(id: string, operations: Array<{ op: "replace"; path: "active" | "displayName" | "role" | "userName"; value: unknown }>): ScimUser | null; deactivateUser(id: string): ScimUser | null; getUser(id: string): ScimUser | null; listUsers(filter?: string): object; };
|
|
18
|
+
export declare function createScimService(config: { organizationId?: string; directory?: ReturnType<typeof createOrganizationDirectory>; bearerToken: string }): { handle(request: { method: string; url: string; headers?: Record<string, string>; body?: any }): { status: number; headers: Record<string, string>; body: any }; directory: ReturnType<typeof createOrganizationDirectory>; };
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Local enterprise-governance primitives for release automation. This module
|
|
4
|
+
// deliberately does not pretend to be an identity provider: SAML/OIDC login,
|
|
5
|
+
// SCIM provisioning, and server-side session enforcement belong in the hosted
|
|
6
|
+
// account service. It provides the shared RBAC, scoped-token, and tamper-evident
|
|
7
|
+
// audit contracts those surfaces can enforce consistently.
|
|
8
|
+
|
|
9
|
+
const crypto = require("crypto");
|
|
10
|
+
|
|
11
|
+
const ROLE_PERMISSIONS = Object.freeze({
|
|
12
|
+
owner: ["protect", "view_evidence", "export_evidence", "manage_projects", "manage_members", "manage_tokens", "manage_billing", "view_audit"],
|
|
13
|
+
admin: ["protect", "view_evidence", "export_evidence", "manage_projects", "manage_members", "manage_tokens", "view_audit"],
|
|
14
|
+
developer: ["protect", "view_evidence", "export_evidence", "manage_projects"],
|
|
15
|
+
reviewer: ["view_evidence", "export_evidence", "view_audit"],
|
|
16
|
+
viewer: ["view_evidence"]
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const TOKEN_SCOPES = Object.freeze(["protect", "evidence:read", "evidence:export", "projects:write", "audit:read"]);
|
|
20
|
+
|
|
21
|
+
function stableJson(value) {
|
|
22
|
+
if (Array.isArray(value)) return "[" + value.map(stableJson).join(",") + "]";
|
|
23
|
+
if (value && typeof value === "object") {
|
|
24
|
+
return "{" + Object.keys(value).sort().map((key) => JSON.stringify(key) + ":" + stableJson(value[key])).join(",") + "}";
|
|
25
|
+
}
|
|
26
|
+
return JSON.stringify(value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sha256(value) {
|
|
30
|
+
return crypto.createHash("sha256").update(String(value), "utf8").digest("hex");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function normalizeMember(member) {
|
|
34
|
+
if (!member || !member.id) throw new Error("governance: member id is required");
|
|
35
|
+
const role = String(member.role || "viewer").toLowerCase();
|
|
36
|
+
if (!ROLE_PERMISSIONS[role]) throw new Error("governance: unknown role '" + role + "'");
|
|
37
|
+
return Object.freeze({ id: String(member.id), role, active: member.active !== false });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function createGovernancePolicy(config) {
|
|
41
|
+
config = config || {};
|
|
42
|
+
const members = new Map((config.members || []).map((member) => {
|
|
43
|
+
const normalized = normalizeMember(member);
|
|
44
|
+
return [normalized.id, normalized];
|
|
45
|
+
}));
|
|
46
|
+
|
|
47
|
+
function authorize(actorId, action) {
|
|
48
|
+
const member = members.get(String(actorId || ""));
|
|
49
|
+
if (!member || !member.active) return { allowed: false, reason: "inactive-or-unknown-member" };
|
|
50
|
+
const allowed = ROLE_PERMISSIONS[member.role].includes(String(action));
|
|
51
|
+
return { allowed, reason: allowed ? "role-allowed" : "role-denied", role: member.role };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
authorize,
|
|
56
|
+
describe: () => ({
|
|
57
|
+
memberCount: members.size,
|
|
58
|
+
roles: Array.from(new Set(Array.from(members.values()).map((member) => member.role))).sort(),
|
|
59
|
+
permissions: ROLE_PERMISSIONS
|
|
60
|
+
})
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createTokenDescriptor(input) {
|
|
65
|
+
input = input || {};
|
|
66
|
+
if (!input.id || !input.createdBy) throw new Error("governance: token id and createdBy are required");
|
|
67
|
+
const scopes = Array.from(new Set((input.scopes || []).map(String))).sort();
|
|
68
|
+
for (const scope of scopes) {
|
|
69
|
+
if (!TOKEN_SCOPES.includes(scope)) throw new Error("governance: unknown token scope '" + scope + "'");
|
|
70
|
+
}
|
|
71
|
+
const expiresAt = input.expiresAt ? new Date(input.expiresAt).toISOString() : null;
|
|
72
|
+
return Object.freeze({
|
|
73
|
+
id: String(input.id),
|
|
74
|
+
name: String(input.name || input.id),
|
|
75
|
+
createdBy: String(input.createdBy),
|
|
76
|
+
scopes,
|
|
77
|
+
expiresAt,
|
|
78
|
+
revokedAt: input.revokedAt ? new Date(input.revokedAt).toISOString() : null
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function authorizeToken(token, scope, now) {
|
|
83
|
+
if (!token || token.revokedAt) return { allowed: false, reason: "revoked-or-missing-token" };
|
|
84
|
+
const clock = now ? new Date(now) : new Date();
|
|
85
|
+
if (token.expiresAt && clock >= new Date(token.expiresAt)) return { allowed: false, reason: "expired-token" };
|
|
86
|
+
const allowed = Array.isArray(token.scopes) && token.scopes.includes(String(scope));
|
|
87
|
+
return { allowed, reason: allowed ? "scope-allowed" : "scope-denied" };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function createAuditTrail(config) {
|
|
91
|
+
config = config || {};
|
|
92
|
+
const organizationId = String(config.organizationId || "");
|
|
93
|
+
if (!organizationId) throw new Error("governance: organizationId is required");
|
|
94
|
+
const events = [];
|
|
95
|
+
|
|
96
|
+
function append(event) {
|
|
97
|
+
event = event || {};
|
|
98
|
+
if (!event.actorId || !event.action) throw new Error("governance: audit actorId and action are required");
|
|
99
|
+
const previousHash = events.length ? events[events.length - 1].hash : null;
|
|
100
|
+
const row = {
|
|
101
|
+
sequence: events.length + 1,
|
|
102
|
+
organizationId,
|
|
103
|
+
actorId: String(event.actorId),
|
|
104
|
+
action: String(event.action),
|
|
105
|
+
target: event.target == null ? null : String(event.target),
|
|
106
|
+
outcome: String(event.outcome || "success"),
|
|
107
|
+
occurredAt: new Date(event.occurredAt || Date.now()).toISOString(),
|
|
108
|
+
metadata: event.metadata && typeof event.metadata === "object" ? event.metadata : {},
|
|
109
|
+
previousHash
|
|
110
|
+
};
|
|
111
|
+
row.hash = sha256(stableJson(row));
|
|
112
|
+
events.push(Object.freeze(row));
|
|
113
|
+
return row;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function verify(rows) {
|
|
117
|
+
rows = rows || events;
|
|
118
|
+
let previousHash = null;
|
|
119
|
+
for (let index = 0; index < rows.length; index++) {
|
|
120
|
+
const row = rows[index];
|
|
121
|
+
if (row.sequence !== index + 1 || row.previousHash !== previousHash) return false;
|
|
122
|
+
const copy = Object.assign({}, row);
|
|
123
|
+
delete copy.hash;
|
|
124
|
+
if (sha256(stableJson(copy)) !== row.hash) return false;
|
|
125
|
+
previousHash = row.hash;
|
|
126
|
+
}
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return { append, verify, events: () => events.slice() };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function validateEnterpriseIdentityConfig(input) {
|
|
134
|
+
input = input || {};
|
|
135
|
+
const protocol = String(input.protocol || "").toLowerCase();
|
|
136
|
+
if (protocol !== "oidc" && protocol !== "saml") throw new Error("governance: identity protocol must be oidc or saml");
|
|
137
|
+
const domains = Array.from(new Set((input.domains || []).map((value) => String(value).trim().toLowerCase()).filter(Boolean)));
|
|
138
|
+
if (!domains.length) throw new Error("governance: at least one verified sign-in domain is required");
|
|
139
|
+
if (protocol === "oidc") {
|
|
140
|
+
if (!/^https:\/\//i.test(String(input.issuer || ""))) throw new Error("governance: OIDC issuer must use https");
|
|
141
|
+
if (!input.clientId) throw new Error("governance: OIDC clientId is required");
|
|
142
|
+
} else {
|
|
143
|
+
if (!/^https:\/\//i.test(String(input.ssoUrl || ""))) throw new Error("governance: SAML ssoUrl must use https");
|
|
144
|
+
if (!input.entityId || !input.certificate) throw new Error("governance: SAML entityId and signing certificate are required");
|
|
145
|
+
}
|
|
146
|
+
return Object.freeze({
|
|
147
|
+
protocol,
|
|
148
|
+
domains: Object.freeze(domains),
|
|
149
|
+
issuer: protocol === "oidc" ? String(input.issuer).replace(/\/+$/, "") : null,
|
|
150
|
+
clientId: protocol === "oidc" ? String(input.clientId) : null,
|
|
151
|
+
ssoUrl: protocol === "saml" ? String(input.ssoUrl) : null,
|
|
152
|
+
entityId: protocol === "saml" ? String(input.entityId) : null,
|
|
153
|
+
certificateFingerprint: protocol === "saml" ? sha256(String(input.certificate).replace(/\s+/g, "")) : null,
|
|
154
|
+
enforceSso: input.enforceSso === true,
|
|
155
|
+
defaultRole: ROLE_PERMISSIONS[String(input.defaultRole || "viewer").toLowerCase()] ? String(input.defaultRole || "viewer").toLowerCase() : "viewer"
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function authenticateEnterprisePrincipal(config, assertion, context) {
|
|
160
|
+
config = config || {};
|
|
161
|
+
assertion = assertion || {};
|
|
162
|
+
context = context || {};
|
|
163
|
+
if (context.signatureVerified !== true) throw new Error("governance: identity assertion signature must be verified by the protocol adapter");
|
|
164
|
+
const nowSeconds = Math.floor(new Date(context.now || Date.now()).getTime() / 1000);
|
|
165
|
+
let email;
|
|
166
|
+
let subject;
|
|
167
|
+
if (config.protocol === "oidc") {
|
|
168
|
+
if (assertion.iss !== config.issuer) throw new Error("governance: OIDC issuer mismatch");
|
|
169
|
+
const audiences = Array.isArray(assertion.aud) ? assertion.aud.map(String) : [String(assertion.aud || "")];
|
|
170
|
+
if (!audiences.includes(config.clientId)) throw new Error("governance: OIDC audience mismatch");
|
|
171
|
+
if (!assertion.exp || Number(assertion.exp) <= nowSeconds) throw new Error("governance: OIDC token expired");
|
|
172
|
+
if (context.nonce && assertion.nonce !== context.nonce) throw new Error("governance: OIDC nonce mismatch");
|
|
173
|
+
if (assertion.email_verified !== true) throw new Error("governance: OIDC email is not verified");
|
|
174
|
+
email = String(assertion.email || "").toLowerCase();
|
|
175
|
+
subject = String(assertion.sub || "");
|
|
176
|
+
} else if (config.protocol === "saml") {
|
|
177
|
+
if (String(assertion.issuer || "") !== config.entityId) throw new Error("governance: SAML issuer mismatch");
|
|
178
|
+
if (context.audience && String(assertion.audience || "") !== String(context.audience)) throw new Error("governance: SAML audience mismatch");
|
|
179
|
+
const nowMs = nowSeconds * 1000;
|
|
180
|
+
if (assertion.notBefore && nowMs < new Date(assertion.notBefore).getTime()) throw new Error("governance: SAML assertion is not active");
|
|
181
|
+
if (!assertion.notOnOrAfter || nowMs >= new Date(assertion.notOnOrAfter).getTime()) throw new Error("governance: SAML assertion expired");
|
|
182
|
+
email = String(assertion.email || assertion.nameId || "").toLowerCase();
|
|
183
|
+
subject = String(assertion.nameId || assertion.subject || "");
|
|
184
|
+
} else {
|
|
185
|
+
throw new Error("governance: validated enterprise identity configuration is required");
|
|
186
|
+
}
|
|
187
|
+
const domain = email.indexOf("@") > 0 ? email.split("@").pop() : "";
|
|
188
|
+
if (!subject || !email || !config.domains.includes(domain)) throw new Error("governance: identity is outside the verified organization domains");
|
|
189
|
+
return Object.freeze({ subject, email, domain, role: config.defaultRole, protocol: config.protocol });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function createOrganizationDirectory(config) {
|
|
193
|
+
config = config || {};
|
|
194
|
+
const organizationId = String(config.organizationId || "");
|
|
195
|
+
if (!organizationId) throw new Error("governance: organizationId is required");
|
|
196
|
+
const users = new Map();
|
|
197
|
+
let sequence = 0;
|
|
198
|
+
|
|
199
|
+
function normalizeUser(input, existing) {
|
|
200
|
+
input = input || {};
|
|
201
|
+
const id = String(input.id || (existing && existing.id) || "");
|
|
202
|
+
const userName = String(input.userName || (existing && existing.userName) || "").trim().toLowerCase();
|
|
203
|
+
if (!id || !userName || userName.indexOf("@") < 1) throw new Error("governance: SCIM user id and email-shaped userName are required");
|
|
204
|
+
const role = String(input.role || (existing && existing.role) || "viewer").toLowerCase();
|
|
205
|
+
if (!ROLE_PERMISSIONS[role]) throw new Error("governance: unknown role '" + role + "'");
|
|
206
|
+
sequence++;
|
|
207
|
+
return Object.freeze({
|
|
208
|
+
schemas: Object.freeze(["urn:ietf:params:scim:schemas:core:2.0:User"]),
|
|
209
|
+
id,
|
|
210
|
+
userName,
|
|
211
|
+
displayName: String(input.displayName || (existing && existing.displayName) || userName),
|
|
212
|
+
role,
|
|
213
|
+
active: input.active !== false,
|
|
214
|
+
organizationId,
|
|
215
|
+
externalId: input.externalId == null ? (existing && existing.externalId) || null : String(input.externalId),
|
|
216
|
+
meta: Object.freeze({ resourceType: "User", version: 'W/"' + sequence + '"' })
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function upsertUser(input) {
|
|
221
|
+
input = input || {};
|
|
222
|
+
const id = String(input.id || (typeof crypto.randomUUID === "function" ? crypto.randomUUID() : crypto.randomBytes(16).toString("hex")));
|
|
223
|
+
const existing = id ? users.get(id) : null;
|
|
224
|
+
const normalized = normalizeUser(Object.assign({}, input, { id }), existing);
|
|
225
|
+
for (const user of users.values()) {
|
|
226
|
+
if (user.id !== normalized.id && user.userName === normalized.userName) throw new Error("governance: SCIM userName already exists");
|
|
227
|
+
}
|
|
228
|
+
users.set(normalized.id, normalized);
|
|
229
|
+
return normalized;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function patchUser(id, operations) {
|
|
233
|
+
const existing = users.get(String(id));
|
|
234
|
+
if (!existing) return null;
|
|
235
|
+
const next = Object.assign({}, existing);
|
|
236
|
+
for (const operation of operations || []) {
|
|
237
|
+
if (String(operation.op || "").toLowerCase() !== "replace") throw new Error("governance: only SCIM replace operations are supported");
|
|
238
|
+
const path = String(operation.path || "");
|
|
239
|
+
if (!["active", "displayName", "role", "userName"].includes(path)) throw new Error("governance: unsupported SCIM patch path '" + path + "'");
|
|
240
|
+
next[path] = operation.value;
|
|
241
|
+
}
|
|
242
|
+
return upsertUser(next);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function deactivateUser(id) {
|
|
246
|
+
return patchUser(id, [{ op: "replace", path: "active", value: false }]);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function listUsers(filter) {
|
|
250
|
+
let result = Array.from(users.values());
|
|
251
|
+
const match = /^\s*(userName|externalId)\s+eq\s+"([^"]+)"\s*$/i.exec(String(filter || ""));
|
|
252
|
+
if (filter && !match) throw new Error("governance: unsupported SCIM filter");
|
|
253
|
+
if (match) result = result.filter((user) => String(user[match[1]] || "").toLowerCase() === match[2].toLowerCase());
|
|
254
|
+
return { schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], totalResults: result.length, startIndex: 1, itemsPerPage: result.length, Resources: result };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
for (const user of config.users || []) upsertUser(user);
|
|
258
|
+
return { organizationId, upsertUser, patchUser, deactivateUser, getUser: (id) => users.get(String(id)) || null, listUsers };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function createScimService(config) {
|
|
262
|
+
config = config || {};
|
|
263
|
+
const directory = config.directory || createOrganizationDirectory(config);
|
|
264
|
+
const tokenHash = sha256(String(config.bearerToken || ""));
|
|
265
|
+
if (!config.bearerToken || String(config.bearerToken).length < 24) throw new Error("governance: SCIM bearer token must be at least 24 characters");
|
|
266
|
+
|
|
267
|
+
function response(status, body) { return { status, headers: { "content-type": "application/scim+json" }, body }; }
|
|
268
|
+
function handle(request) {
|
|
269
|
+
request = request || {};
|
|
270
|
+
const auth = String((request.headers && (request.headers.authorization || request.headers.Authorization)) || "");
|
|
271
|
+
const supplied = auth.replace(/^Bearer\s+/i, "");
|
|
272
|
+
const expectedBuffer = Buffer.from(tokenHash, "hex");
|
|
273
|
+
const suppliedBuffer = Buffer.from(sha256(supplied), "hex");
|
|
274
|
+
if (!supplied || !crypto.timingSafeEqual(expectedBuffer, suppliedBuffer)) return response(401, { schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"], status: "401", detail: "invalid bearer token" });
|
|
275
|
+
const method = String(request.method || "GET").toUpperCase();
|
|
276
|
+
const parsed = new URL(String(request.url || "/Users"), "https://scim.invalid");
|
|
277
|
+
const userMatch = /^\/Users(?:\/([^/]+))?$/.exec(parsed.pathname);
|
|
278
|
+
if (!userMatch) return response(404, { status: "404", detail: "resource not found" });
|
|
279
|
+
const id = userMatch[1] ? decodeURIComponent(userMatch[1]) : null;
|
|
280
|
+
try {
|
|
281
|
+
if (method === "GET" && !id) return response(200, directory.listUsers(parsed.searchParams.get("filter")));
|
|
282
|
+
if (method === "GET" && id) { const user = directory.getUser(id); return user ? response(200, user) : response(404, { status: "404", detail: "user not found" }); }
|
|
283
|
+
if (method === "POST" && !id) return response(201, directory.upsertUser(request.body));
|
|
284
|
+
if ((method === "PUT" || method === "PATCH") && id) {
|
|
285
|
+
const body = request.body || {};
|
|
286
|
+
const user = method === "PATCH" ? directory.patchUser(id, body.Operations || body.operations) : directory.upsertUser(Object.assign({}, body, { id }));
|
|
287
|
+
return user ? response(200, user) : response(404, { status: "404", detail: "user not found" });
|
|
288
|
+
}
|
|
289
|
+
if (method === "DELETE" && id) return directory.deactivateUser(id) ? response(204, null) : response(404, { status: "404", detail: "user not found" });
|
|
290
|
+
return response(405, { status: "405", detail: "method not allowed" });
|
|
291
|
+
} catch (error) {
|
|
292
|
+
return response(400, { schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"], status: "400", detail: error.message });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return { handle, directory };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
module.exports = {
|
|
299
|
+
ROLE_PERMISSIONS,
|
|
300
|
+
TOKEN_SCOPES,
|
|
301
|
+
createGovernancePolicy,
|
|
302
|
+
createTokenDescriptor,
|
|
303
|
+
authorizeToken,
|
|
304
|
+
createAuditTrail,
|
|
305
|
+
validateEnterpriseIdentityConfig,
|
|
306
|
+
authenticateEnterprisePrincipal,
|
|
307
|
+
createOrganizationDirectory,
|
|
308
|
+
createScimService
|
|
309
|
+
};
|
package/grunt.d.ts
ADDED
package/grunt.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { assertSizeBudgets, buildItemsManifest, buildProtectionItemsFromInputItems, composeProtectionItemOutput, createProtectionConfig, isExcluded, protectItems, writeManifest } = require("./index.js");
|
|
6
|
+
|
|
7
|
+
function registerJsoProtectorGrunt(grunt) {
|
|
8
|
+
grunt.registerMultiTask("jsoProtector", "Protect JavaScript files with the JavaScript Obfuscator HTTP API.", function task() {
|
|
9
|
+
const done = this.async();
|
|
10
|
+
const options = this.options({});
|
|
11
|
+
const config = createProtectionConfig(options);
|
|
12
|
+
|
|
13
|
+
runGruntTask(grunt, this.files || [], config)
|
|
14
|
+
.then(() => done())
|
|
15
|
+
.catch((error) => done(error));
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function runGruntTask(grunt, fileGroups, config) {
|
|
20
|
+
const files = collectGruntFiles(grunt, fileGroups, config);
|
|
21
|
+
if (!files.length) return;
|
|
22
|
+
|
|
23
|
+
const inputItems = files.map((file) => ({
|
|
24
|
+
FileName: file.fileName,
|
|
25
|
+
FileCode: grunt.file.read(file.source),
|
|
26
|
+
SourcePath: file.source,
|
|
27
|
+
OutputPath: file.target
|
|
28
|
+
}));
|
|
29
|
+
const protection = buildProtectionItemsFromInputItems(config, inputItems);
|
|
30
|
+
const result = await protectItems(config, protection.items);
|
|
31
|
+
const manifest = buildItemsManifest(config, inputItems, result, (fileName) => {
|
|
32
|
+
const found = files.find((file) => normalizeName(file.fileName) === normalizeName(fileName));
|
|
33
|
+
return found ? found.target : fileName;
|
|
34
|
+
}, protection.transforms);
|
|
35
|
+
assertSizeBudgets(manifest, config);
|
|
36
|
+
|
|
37
|
+
for (const file of files) {
|
|
38
|
+
grunt.file.mkdir(path.dirname(file.target));
|
|
39
|
+
grunt.file.write(file.target, composeProtectionItemOutput(file.fileName, result, protection.transforms, config));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (config.manifest) {
|
|
43
|
+
writeManifest(config.manifest, manifest);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function collectGruntFiles(grunt, fileGroups, config) {
|
|
48
|
+
const files = [];
|
|
49
|
+
for (const group of fileGroups || []) {
|
|
50
|
+
const sources = Array.isArray(group.src) ? group.src : [group.src].filter(Boolean);
|
|
51
|
+
for (const source of sources) {
|
|
52
|
+
if (!source || !grunt.file.exists(source)) continue;
|
|
53
|
+
const target = targetPathForGroup(source, group);
|
|
54
|
+
const fileName = assetNameForFile(source, target, config);
|
|
55
|
+
if (!shouldProtect(fileName, config)) continue;
|
|
56
|
+
files.push({ source, target, fileName });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return files;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function targetPathForGroup(source, group) {
|
|
63
|
+
if (!group.dest) return source;
|
|
64
|
+
const sourceCount = Array.isArray(group.src) ? group.src.length : 1;
|
|
65
|
+
if (sourceCount > 1 || looksLikeDirectory(group.dest)) {
|
|
66
|
+
return path.join(group.dest, path.basename(source));
|
|
67
|
+
}
|
|
68
|
+
return group.dest;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function looksLikeDirectory(value) {
|
|
72
|
+
return /[\\/]$/.test(String(value || ""));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function assetNameForFile(source, target, config) {
|
|
76
|
+
const output = config.output ? path.resolve(config.output) : "";
|
|
77
|
+
const resolvedTarget = path.resolve(target || source);
|
|
78
|
+
if (output && isInside(output, resolvedTarget)) {
|
|
79
|
+
return normalizeName(path.relative(output, resolvedTarget));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const input = config.input ? path.resolve(config.input) : "";
|
|
83
|
+
const resolvedSource = path.resolve(source);
|
|
84
|
+
if (input && isInside(input, resolvedSource)) {
|
|
85
|
+
return normalizeName(path.relative(input, resolvedSource));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return normalizeName(path.basename(target || source));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function shouldProtect(fileName, config) {
|
|
92
|
+
if (!fileName.endsWith(".js")) return false;
|
|
93
|
+
if (Array.isArray(config.include) && config.include.length && !isExcluded(fileName, config.include)) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
return !isExcluded(fileName, config.exclude || []);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isInside(root, filePath) {
|
|
100
|
+
const relative = path.relative(root, filePath);
|
|
101
|
+
return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function normalizeName(name) {
|
|
105
|
+
return String(name || "").replace(/\\/g, "/");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
module.exports = registerJsoProtectorGrunt;
|
|
109
|
+
module.exports.registerJsoProtectorGrunt = registerJsoProtectorGrunt;
|
|
110
|
+
module.exports._runGruntTask = runGruntTask;
|
|
111
|
+
module.exports.default = registerJsoProtectorGrunt;
|
package/gulp.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ProtectionOptions } from "./index";
|
|
2
|
+
|
|
3
|
+
export interface JsoProtectorGulpOptions extends ProtectionOptions {
|
|
4
|
+
removeSourceMaps?: boolean;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
declare function jsoProtector(options?: JsoProtectorGulpOptions): NodeJS.ReadWriteStream;
|
|
8
|
+
|
|
9
|
+
export { jsoProtector };
|
|
10
|
+
export default jsoProtector;
|
package/gulp.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const path = require("path");
|
|
4
|
+
const { Transform } = require("stream");
|
|
5
|
+
const { assertSizeBudgets, buildItemsManifest, buildProtectionItemsFromInputItems, composeProtectionItemOutput, createProtectionConfig, isExcluded, protectItems, writeManifest } = require("./index.js");
|
|
6
|
+
|
|
7
|
+
function jsoProtector(options = {}) {
|
|
8
|
+
const config = createProtectionConfig(options);
|
|
9
|
+
const removeSourceMaps = options.removeSourceMaps !== false;
|
|
10
|
+
const files = [];
|
|
11
|
+
|
|
12
|
+
return new Transform({
|
|
13
|
+
objectMode: true,
|
|
14
|
+
transform(file, _encoding, callback) {
|
|
15
|
+
if (!file) {
|
|
16
|
+
callback();
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (typeof file.isStream === "function" && file.isStream()) {
|
|
20
|
+
callback(new Error("jso-protector does not support streaming Vinyl contents. Use buffered files."));
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
files.push(file);
|
|
24
|
+
callback();
|
|
25
|
+
},
|
|
26
|
+
async flush(callback) {
|
|
27
|
+
try {
|
|
28
|
+
const targets = files.filter((file) => shouldProtectFile(file, config));
|
|
29
|
+
const inputItems = targets.map((file) => ({
|
|
30
|
+
FileName: assetNameForFile(file),
|
|
31
|
+
FileCode: contentsToString(file.contents),
|
|
32
|
+
SourcePath: file.path || assetNameForFile(file),
|
|
33
|
+
OutputPath: file.path || assetNameForFile(file)
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
let result = null;
|
|
37
|
+
let protection = { items: [], transforms: new Map() };
|
|
38
|
+
let manifest = null;
|
|
39
|
+
if (inputItems.length) {
|
|
40
|
+
protection = buildProtectionItemsFromInputItems(config, inputItems);
|
|
41
|
+
result = await protectItems(config, protection.items);
|
|
42
|
+
manifest = buildItemsManifest(config, inputItems, result, (fileName) => {
|
|
43
|
+
const found = targets.find((target) => normalizeName(assetNameForFile(target)) === normalizeName(fileName));
|
|
44
|
+
return found && found.path ? found.path : fileName;
|
|
45
|
+
}, protection.transforms);
|
|
46
|
+
assertSizeBudgets(manifest, config);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const file of files) {
|
|
50
|
+
if (removeSourceMaps && assetNameForFile(file).endsWith(".js.map")) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (shouldProtectFile(file, config)) {
|
|
55
|
+
const assetName = assetNameForFile(file);
|
|
56
|
+
file.contents = Buffer.from(composeProtectionItemOutput(assetName, result, protection.transforms, config), "utf8");
|
|
57
|
+
}
|
|
58
|
+
this.push(file);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (config.manifest && manifest) {
|
|
62
|
+
writeManifest(config.manifest, manifest);
|
|
63
|
+
}
|
|
64
|
+
callback();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
callback(error);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function shouldProtectFile(file, config) {
|
|
73
|
+
if (!file || (typeof file.isNull === "function" && file.isNull())) return false;
|
|
74
|
+
const assetName = assetNameForFile(file);
|
|
75
|
+
if (!assetName.endsWith(".js")) return false;
|
|
76
|
+
if (Array.isArray(config.include) && config.include.length && !isExcluded(assetName, config.include)) {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
return !isExcluded(assetName, config.exclude || []);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function assetNameForFile(file) {
|
|
83
|
+
if (file && typeof file.relative === "string" && file.relative) {
|
|
84
|
+
return normalizeName(file.relative);
|
|
85
|
+
}
|
|
86
|
+
if (file && file.path && file.base) {
|
|
87
|
+
return normalizeName(path.relative(file.base, file.path));
|
|
88
|
+
}
|
|
89
|
+
if (file && file.path) {
|
|
90
|
+
return normalizeName(path.basename(file.path));
|
|
91
|
+
}
|
|
92
|
+
return "";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function contentsToString(contents) {
|
|
96
|
+
if (!contents) return "";
|
|
97
|
+
return Buffer.isBuffer(contents) ? contents.toString("utf8") : String(contents);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function normalizeName(name) {
|
|
101
|
+
return String(name || "").replace(/\\/g, "/");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = jsoProtector;
|
|
105
|
+
module.exports.jsoProtector = jsoProtector;
|
|
106
|
+
module.exports.default = jsoProtector;
|