@gadicc/loom 1.35.3 → 1.37.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 +66 -0
- package/THIRD_PARTY_NOTICES.md +12 -9
- package/esm/src/cli/externalSkills.d.ts.map +1 -1
- package/esm/src/cli/externalSkills.js +25 -20
- package/esm/src/cli/mod.d.ts +117 -1
- package/esm/src/cli/mod.d.ts.map +1 -1
- package/esm/src/cli/mod.js +1368 -44
- package/esm/src/cli/projectSkills.d.ts +10 -3
- package/esm/src/cli/projectSkills.d.ts.map +1 -1
- package/esm/src/cli/projectSkills.js +173 -49
- package/esm/src/cli/vercelBuildEnv.d.ts +28 -0
- package/esm/src/cli/vercelBuildEnv.d.ts.map +1 -1
- package/esm/src/cli/vercelBuildEnv.js +120 -30
- package/esm/src/next/secrets/mod.d.ts +108 -0
- package/esm/src/next/secrets/mod.d.ts.map +1 -0
- package/esm/src/next/secrets/mod.js +176 -0
- package/esm/src/secrets/encoding.d.ts +32 -0
- package/esm/src/secrets/encoding.d.ts.map +1 -0
- package/esm/src/secrets/encoding.js +87 -0
- package/esm/src/secrets/errors.d.ts +45 -0
- package/esm/src/secrets/errors.d.ts.map +1 -0
- package/esm/src/secrets/errors.js +39 -0
- package/esm/src/secrets/fingerprint.d.ts +43 -0
- package/esm/src/secrets/fingerprint.d.ts.map +1 -0
- package/esm/src/secrets/fingerprint.js +87 -0
- package/esm/src/secrets/frame.d.ts +34 -0
- package/esm/src/secrets/frame.d.ts.map +1 -0
- package/esm/src/secrets/frame.js +86 -0
- package/esm/src/secrets/keyring.d.ts +62 -0
- package/esm/src/secrets/keyring.d.ts.map +1 -0
- package/esm/src/secrets/keyring.js +160 -0
- package/esm/src/secrets/legacy.d.ts +60 -0
- package/esm/src/secrets/legacy.d.ts.map +1 -0
- package/esm/src/secrets/legacy.js +147 -0
- package/esm/src/secrets/maintenance.d.ts +173 -0
- package/esm/src/secrets/maintenance.d.ts.map +1 -0
- package/esm/src/secrets/maintenance.js +315 -0
- package/esm/src/secrets/mod.d.ts +6 -0
- package/esm/src/secrets/mod.d.ts.map +1 -0
- package/esm/src/secrets/mod.js +5 -0
- package/esm/src/secrets/secrets.d.ts +192 -0
- package/esm/src/secrets/secrets.d.ts.map +1 -0
- package/esm/src/secrets/secrets.js +528 -0
- package/package.json +50 -2
- package/script/src/cli/externalSkills.d.ts.map +1 -1
- package/script/src/cli/externalSkills.js +25 -20
- package/script/src/cli/mod.d.ts +117 -1
- package/script/src/cli/mod.d.ts.map +1 -1
- package/script/src/cli/mod.js +1372 -41
- package/script/src/cli/projectSkills.d.ts +10 -3
- package/script/src/cli/projectSkills.d.ts.map +1 -1
- package/script/src/cli/projectSkills.js +173 -49
- package/script/src/cli/vercelBuildEnv.d.ts +28 -0
- package/script/src/cli/vercelBuildEnv.d.ts.map +1 -1
- package/script/src/cli/vercelBuildEnv.js +121 -30
- package/script/src/next/secrets/mod.d.ts +108 -0
- package/script/src/next/secrets/mod.d.ts.map +1 -0
- package/script/src/next/secrets/mod.js +218 -0
- package/script/src/secrets/encoding.d.ts +32 -0
- package/script/src/secrets/encoding.d.ts.map +1 -0
- package/script/src/secrets/encoding.js +95 -0
- package/script/src/secrets/errors.d.ts +45 -0
- package/script/src/secrets/errors.d.ts.map +1 -0
- package/script/src/secrets/errors.js +45 -0
- package/script/src/secrets/fingerprint.d.ts +43 -0
- package/script/src/secrets/fingerprint.d.ts.map +1 -0
- package/script/src/secrets/fingerprint.js +92 -0
- package/script/src/secrets/frame.d.ts +34 -0
- package/script/src/secrets/frame.d.ts.map +1 -0
- package/script/src/secrets/frame.js +91 -0
- package/script/src/secrets/keyring.d.ts +62 -0
- package/script/src/secrets/keyring.d.ts.map +1 -0
- package/script/src/secrets/keyring.js +202 -0
- package/script/src/secrets/legacy.d.ts +60 -0
- package/script/src/secrets/legacy.d.ts.map +1 -0
- package/script/src/secrets/legacy.js +186 -0
- package/script/src/secrets/maintenance.d.ts +173 -0
- package/script/src/secrets/maintenance.d.ts.map +1 -0
- package/script/src/secrets/maintenance.js +323 -0
- package/script/src/secrets/mod.d.ts +6 -0
- package/script/src/secrets/mod.d.ts.map +1 -0
- package/script/src/secrets/mod.js +24 -0
- package/script/src/secrets/secrets.d.ts +192 -0
- package/script/src/secrets/secrets.d.ts.map +1 -0
- package/script/src/secrets/secrets.js +532 -0
- package/skills/loom/SKILL.md +79 -222
- package/skills/loom/references/dependency-upgrades.md +26 -0
- package/skills/loom/references/local-development.md +157 -0
- package/skills/loom/references/release-safety.md +118 -0
- package/skills/loom/references/release-trusted-sources.md +55 -0
- package/skills/loom/references/tools-and-skills.md +83 -0
- package/skills/loom-api-keys/SKILL.md +1 -1
- package/skills/loom-auth/SKILL.md +7 -60
- package/skills/loom-auth/references/secrets-and-rotation.md +61 -0
- package/skills/loom-db/SKILL.md +4 -79
- package/skills/loom-files/SKILL.md +4 -2
- package/skills/loom-files/references/provider-configuration.md +150 -0
- package/skills/loom-jobs/SKILL.md +9 -8
- package/skills/loom-lingui/SKILL.md +5 -3
- package/skills/loom-secrets/SKILL.md +266 -0
- package/skills/loom-torvalds-review/SKILL.md +9 -6
- package/skills/loom-torvalds-review/references/context-profiles.md +2 -1
- package/skills/upgrade-deps/SKILL.md +15 -7
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.isUsablePulledValue = isUsablePulledValue;
|
|
4
|
+
exports.parseVercelBuildEnvironmentPolicy = parseVercelBuildEnvironmentPolicy;
|
|
4
5
|
exports.prepareVercelBuildEnvironment = prepareVercelBuildEnvironment;
|
|
5
6
|
exports.verifyVercelBuildArtifact = verifyVercelBuildArtifact;
|
|
6
7
|
const node_crypto_1 = require("node:crypto");
|
|
@@ -10,14 +11,34 @@ const node_util_1 = require("node:util");
|
|
|
10
11
|
function readJson(path) {
|
|
11
12
|
return JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
|
|
12
13
|
}
|
|
13
|
-
function
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
14
|
+
function entryTargets(entry) {
|
|
15
|
+
return Array.isArray(entry.target) ? entry.target : [entry.target];
|
|
16
|
+
}
|
|
17
|
+
function productionEntries(envs, matches) {
|
|
18
|
+
return envs.filter((entry) => typeof entry.key === "string" &&
|
|
19
|
+
matches(entry.key) &&
|
|
20
|
+
entryTargets(entry).includes("production"));
|
|
21
|
+
}
|
|
22
|
+
function compileKeyPattern(source, name) {
|
|
23
|
+
if (typeof source !== "string" || !source) {
|
|
24
|
+
throw new Error(`Environment requirement "${name}" has an invalid keyPattern.`);
|
|
25
|
+
}
|
|
26
|
+
// An odd number of backslashes before the final `$` escapes it.
|
|
27
|
+
const trailingBackslashes = source.slice(0, -1).match(/\\*$/)?.[0].length ??
|
|
28
|
+
0;
|
|
29
|
+
if (source.length < 2 || !source.startsWith("^") || !source.endsWith("$") ||
|
|
30
|
+
trailingBackslashes % 2 === 1) {
|
|
31
|
+
throw new Error(`Environment requirement "${name}" keyPattern must be anchored with ^ and $: ${source}`);
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
new RegExp(source);
|
|
35
|
+
// Grouping the body keeps a top-level alternative such as `^A|B$` inside
|
|
36
|
+
// the anchors, so it cannot match part of an unrelated variable name.
|
|
37
|
+
return new RegExp(`^(?:${source.slice(1, -1)})$`);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error(`Environment requirement "${name}" keyPattern is not a valid regular expression: ${source}`);
|
|
41
|
+
}
|
|
21
42
|
}
|
|
22
43
|
function isUsablePulledValue(value) {
|
|
23
44
|
return Boolean(value?.trim()) &&
|
|
@@ -62,29 +83,66 @@ function parsePolicyRequirement(value, index) {
|
|
|
62
83
|
const keys = Array.isArray(requirement.keys)
|
|
63
84
|
? requirement.keys.filter((key) => typeof key === "string" && Boolean(key))
|
|
64
85
|
: [];
|
|
65
|
-
|
|
86
|
+
const hasPattern = requirement.keyPattern !== undefined;
|
|
87
|
+
if (hasPattern && requirement.keys !== undefined) {
|
|
88
|
+
throw new Error(`Environment requirement "${name}" must have either keys or keyPattern, not both.`);
|
|
89
|
+
}
|
|
90
|
+
if (!hasPattern && keys.length === 0) {
|
|
66
91
|
throw new Error(`Environment requirement "${name}" has no keys.`);
|
|
67
92
|
}
|
|
93
|
+
const pattern = hasPattern
|
|
94
|
+
? compileKeyPattern(requirement.keyPattern, name)
|
|
95
|
+
: undefined;
|
|
68
96
|
let placeholder;
|
|
69
97
|
if (requirement.placeholder !== undefined) {
|
|
70
98
|
if (typeof requirement.placeholder !== "object" ||
|
|
71
99
|
requirement.placeholder === null ||
|
|
72
|
-
typeof requirement.placeholder.key !== "string" ||
|
|
73
100
|
typeof requirement.placeholder.kind !== "string") {
|
|
74
101
|
throw new Error(`Environment requirement "${name}" has an invalid placeholder policy.`);
|
|
75
102
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
103
|
+
if (pattern) {
|
|
104
|
+
// The placeholder goes to each matched variable, so naming one is a
|
|
105
|
+
// mistake rather than something to ignore.
|
|
106
|
+
if (requirement.placeholder.key !== undefined) {
|
|
107
|
+
throw new Error(`Environment requirement "${name}" uses keyPattern, so its placeholder must not name a key.`);
|
|
108
|
+
}
|
|
109
|
+
placeholder = { kind: requirement.placeholder.kind };
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
if (typeof requirement.placeholder.key !== "string") {
|
|
113
|
+
throw new Error(`Environment requirement "${name}" has an invalid placeholder policy.`);
|
|
114
|
+
}
|
|
115
|
+
placeholder = {
|
|
116
|
+
key: requirement.placeholder.key,
|
|
117
|
+
kind: requirement.placeholder.kind,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
80
120
|
}
|
|
121
|
+
const keySet = new Set(keys);
|
|
81
122
|
return {
|
|
123
|
+
keyPattern: pattern ? requirement.keyPattern : undefined,
|
|
82
124
|
keys,
|
|
125
|
+
matches: pattern ? (key) => pattern.test(key) : (key) => keySet.has(key),
|
|
83
126
|
name,
|
|
84
127
|
placeholder,
|
|
128
|
+
productionOnly: requirement.productionOnly === true,
|
|
85
129
|
sensitive: requirement.sensitive === true,
|
|
86
130
|
};
|
|
87
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* Validates a Vercel build environment policy (the app's
|
|
134
|
+
* `.github/vercel-production-env.json`) and returns its requirements. Throws
|
|
135
|
+
* naming the requirement that is wrong.
|
|
136
|
+
*/
|
|
137
|
+
function parseVercelBuildEnvironmentPolicy(policy) {
|
|
138
|
+
const requirements = typeof policy === "object" && policy !== null
|
|
139
|
+
? policy.requirements
|
|
140
|
+
: undefined;
|
|
141
|
+
if (!Array.isArray(requirements)) {
|
|
142
|
+
throw new Error("Vercel environment policy has no requirements array.");
|
|
143
|
+
}
|
|
144
|
+
return requirements.map((value, index) => parsePolicyRequirement(value, index));
|
|
145
|
+
}
|
|
88
146
|
/**
|
|
89
147
|
* Validates required Production variables and fills unreadable Sensitive values
|
|
90
148
|
* with unique build-only placeholders without replacing readable pulled values.
|
|
@@ -100,15 +158,19 @@ function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataFile, po
|
|
|
100
158
|
if (!Array.isArray(envs)) {
|
|
101
159
|
throw new Error("Vercel metadata did not contain an envs array.");
|
|
102
160
|
}
|
|
103
|
-
|
|
104
|
-
throw new Error("Vercel environment policy has no requirements array.");
|
|
105
|
-
}
|
|
161
|
+
const requirements = parseVercelBuildEnvironmentPolicy(policy);
|
|
106
162
|
const placeholders = [];
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
|
|
163
|
+
const addPlaceholder = (key, kind, requirement) => {
|
|
164
|
+
const placeholder = buildPlaceholder(kind);
|
|
165
|
+
envSource = setEnvValue(envSource, key, placeholder.value);
|
|
166
|
+
pulledValues[key] = placeholder.value;
|
|
167
|
+
placeholders.push({ key, marker: placeholder.marker, requirement });
|
|
168
|
+
io.out(`Added a build-only ${key} placeholder for ${requirement}.`);
|
|
169
|
+
};
|
|
170
|
+
for (const requirement of requirements) {
|
|
171
|
+
const entries = productionEntries(envs, requirement.matches);
|
|
110
172
|
if (entries.length === 0) {
|
|
111
|
-
throw new Error(`Missing Vercel Production variable for ${requirement.name}: ${requirement.keys.join(" or ")}`);
|
|
173
|
+
throw new Error(`Missing Vercel Production variable for ${requirement.name}: ${requirement.keyPattern ?? requirement.keys.join(" or ")}`);
|
|
112
174
|
}
|
|
113
175
|
const nonSensitive = entries.filter((entry) => entry.type !== "sensitive");
|
|
114
176
|
if (requirement.sensitive && nonSensitive.length > 0) {
|
|
@@ -116,6 +178,43 @@ function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataFile, po
|
|
|
116
178
|
.map((entry) => entry.key)
|
|
117
179
|
.join(", ")}`);
|
|
118
180
|
}
|
|
181
|
+
const shared = entries.filter((entry) => {
|
|
182
|
+
const targets = entryTargets(entry);
|
|
183
|
+
if (targets.length !== 1 || targets[0] !== "production")
|
|
184
|
+
return true;
|
|
185
|
+
// Vercel lists custom environments beside `target`, so a variable
|
|
186
|
+
// attached to one is shared even though it targets only Production.
|
|
187
|
+
// Anything but an absent or empty list counts as shared.
|
|
188
|
+
const custom = entry.customEnvironmentIds;
|
|
189
|
+
return custom !== undefined && custom !== null &&
|
|
190
|
+
!(Array.isArray(custom) && custom.length === 0);
|
|
191
|
+
});
|
|
192
|
+
if (requirement.productionOnly && shared.length > 0) {
|
|
193
|
+
throw new Error(`Vercel Production variable must target Production only for ${requirement.name}: ${shared
|
|
194
|
+
.map((entry) => entry.key)
|
|
195
|
+
.join(", ")}`);
|
|
196
|
+
}
|
|
197
|
+
if (requirement.keyPattern !== undefined) {
|
|
198
|
+
// Every matched variable is needed, not one of several alternatives,
|
|
199
|
+
// so each gets its own verdict and, when unreadable, its own placeholder.
|
|
200
|
+
const matchedKeys = [
|
|
201
|
+
...new Set(entries.map((entry) => entry.key)),
|
|
202
|
+
];
|
|
203
|
+
for (const key of matchedKeys) {
|
|
204
|
+
if (isUsablePulledValue(pulledValues[key])) {
|
|
205
|
+
io.out(`Verified ${requirement.name} from vercel pull (${key}).`);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (entries.some((entry) => entry.key === key && entry.type !== "sensitive")) {
|
|
209
|
+
throw new Error(`Vercel Production variable is empty after pull for ${requirement.name}: ${key}`);
|
|
210
|
+
}
|
|
211
|
+
if (!requirement.placeholder) {
|
|
212
|
+
throw new Error(`Sensitive Vercel Production variable has no build placeholder policy for ${requirement.name}.`);
|
|
213
|
+
}
|
|
214
|
+
addPlaceholder(key, requirement.placeholder.kind, requirement.name);
|
|
215
|
+
}
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
119
218
|
const pulledKey = requirement.keys.find((key) => isUsablePulledValue(pulledValues[key]));
|
|
120
219
|
if (pulledKey) {
|
|
121
220
|
io.out(`Verified ${requirement.name} from vercel pull (${pulledKey}).`);
|
|
@@ -133,15 +232,7 @@ function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataFile, po
|
|
|
133
232
|
io.out(`Preserved pulled ${placeholderKey} for ${requirement.name}.`);
|
|
134
233
|
continue;
|
|
135
234
|
}
|
|
136
|
-
|
|
137
|
-
envSource = setEnvValue(envSource, placeholderKey, placeholder.value);
|
|
138
|
-
pulledValues[placeholderKey] = placeholder.value;
|
|
139
|
-
placeholders.push({
|
|
140
|
-
key: placeholderKey,
|
|
141
|
-
marker: placeholder.marker,
|
|
142
|
-
requirement: requirement.name,
|
|
143
|
-
});
|
|
144
|
-
io.out(`Added a build-only ${placeholderKey} placeholder for ${requirement.name}.`);
|
|
235
|
+
addPlaceholder(placeholderKey, requirement.placeholder.kind, requirement.name);
|
|
145
236
|
}
|
|
146
237
|
(0, node_fs_1.writeFileSync)(envFile, envSource, { mode: 0o600 });
|
|
147
238
|
(0, node_fs_1.writeFileSync)(manifestFile, `${JSON.stringify({ placeholders }, null, 2)}\n`, { mode: 0o600 });
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import "../../../_dnt.polyfills.js";
|
|
2
|
+
import { type CreateSecretsOptions, type SecretKeyring, type Secrets, SecretsKeyError } from "../../secrets/mod.js";
|
|
3
|
+
export * from "../../secrets/mod.js";
|
|
4
|
+
declare const ENVIRONMENTS: readonly ["production", "preview", "development"];
|
|
5
|
+
type NextSecretsEnv = Record<string, string | undefined>;
|
|
6
|
+
/** Deployment environments an expected-key list can be recorded for. */
|
|
7
|
+
export type SecretsEnvironment = (typeof ENVIRONMENTS)[number];
|
|
8
|
+
/** One recorded key as it appears in JSON, before validation. */
|
|
9
|
+
export interface RecordedSecretKey {
|
|
10
|
+
id: number;
|
|
11
|
+
fingerprint: string;
|
|
12
|
+
/** `active`, `decrypt-only` or `retired`; a JSON import types it as string. */
|
|
13
|
+
state: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Expected keys per environment, in the shape `loom` records them under
|
|
17
|
+
* `features.secrets.config.keys` in `loom.json`, so that object can be passed
|
|
18
|
+
* straight in. Every list is validated when the secrets are created. An
|
|
19
|
+
* absent or empty list means none was recorded for that environment.
|
|
20
|
+
* Development keys are per machine and gitignored, so they have no list.
|
|
21
|
+
*/
|
|
22
|
+
export interface NextSecretsExpectedKeys {
|
|
23
|
+
production?: readonly RecordedSecretKey[] | undefined;
|
|
24
|
+
preview?: readonly RecordedSecretKey[] | undefined;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Variable names, in the shape `loom` records them under
|
|
28
|
+
* `features.secrets.config.env` in `loom.json`.
|
|
29
|
+
*/
|
|
30
|
+
export interface NextSecretsVariables {
|
|
31
|
+
keyPrefix?: string | undefined;
|
|
32
|
+
activeKeyName?: string | undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Options for {@link createNextSecrets}. */
|
|
35
|
+
export interface CreateNextSecretsOptions extends Omit<CreateSecretsOptions, "keys" | "expectedKeys"> {
|
|
36
|
+
/** Defaults to the environment keyring (`LOOM_SECRETS_KEY_<n>`). */
|
|
37
|
+
keys?: SecretKeyring | undefined;
|
|
38
|
+
/** Variable names for the default keyring. Ignored when `keys` is given. */
|
|
39
|
+
variables?: NextSecretsVariables | undefined;
|
|
40
|
+
expectedKeys?: NextSecretsExpectedKeys | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Which environment's key list applies. Defaults to the
|
|
43
|
+
* `LOOM_SECRETS_ENVIRONMENT` variable, then `VERCEL_ENV`. A host that
|
|
44
|
+
* provides neither must set one of them: otherwise production cannot be
|
|
45
|
+
* told from development, and a recorded list would be silently ignored.
|
|
46
|
+
* When the two variables name different environments every operation is
|
|
47
|
+
* refused; passing this option skips that comparison.
|
|
48
|
+
*/
|
|
49
|
+
environment?: SecretsEnvironment | undefined;
|
|
50
|
+
/**
|
|
51
|
+
* Allow `assertReady()` to pass in production when no key list is recorded.
|
|
52
|
+
* Off by default: in production, a missing list means nothing shows that
|
|
53
|
+
* the deployed key is the one the operator saved.
|
|
54
|
+
*/
|
|
55
|
+
allowUnverifiedProduction?: boolean | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Allow secrets to be used while `next build` prerenders. Off by default: a
|
|
58
|
+
* page prerendered at build time would bake a decrypted value, or an
|
|
59
|
+
* "unreadable" state, into static output, and release builds substitute
|
|
60
|
+
* placeholders for keys they cannot read. Do not set it to make a failing
|
|
61
|
+
* build pass; make the route dynamic instead.
|
|
62
|
+
*/
|
|
63
|
+
allowDuringBuild?: boolean | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* The environment object the default keyring reads key values from.
|
|
66
|
+
* Defaults to `process.env`. It is not the manifest's `env` section, which
|
|
67
|
+
* holds variable names and belongs in `variables`, and it is not where the
|
|
68
|
+
* build phase or the deployment environment is read from: see `runtimeEnv`.
|
|
69
|
+
*/
|
|
70
|
+
keysEnv?: NextSecretsEnv | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* Where `NEXT_PHASE`, `LOOM_SECRETS_ENVIRONMENT`, `VERCEL_ENV` and
|
|
73
|
+
* `NODE_ENV` are read from. Defaults to
|
|
74
|
+
* `process.env`. For tests only: an app that narrows its environment into
|
|
75
|
+
* its own object must not hide these from the checks that depend on them.
|
|
76
|
+
*/
|
|
77
|
+
runtimeEnv?: NextSecretsEnv | undefined;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Secrets were used while `next build` was prerendering. Make the route
|
|
81
|
+
* dynamic, so that it runs per request with the deployment's real keys.
|
|
82
|
+
*/
|
|
83
|
+
export declare class SecretsBuildPhaseError extends SecretsKeyError {
|
|
84
|
+
constructor();
|
|
85
|
+
}
|
|
86
|
+
/** Names the environment explicitly where `VERCEL_ENV` is not available. */
|
|
87
|
+
export declare const SECRETS_ENVIRONMENT_ENV = "LOOM_SECRETS_ENVIRONMENT";
|
|
88
|
+
/**
|
|
89
|
+
* The environment whose expected-key list applies, or `null` when it cannot
|
|
90
|
+
* be told. `LOOM_SECRETS_ENVIRONMENT` wins over `VERCEL_ENV`: set it on hosts
|
|
91
|
+
* other than Vercel, and to `development` in `.env.local` to run a production
|
|
92
|
+
* build locally. When both are set and disagree this still returns the
|
|
93
|
+
* explicit one, but `createNextSecrets` refuses every operation.
|
|
94
|
+
*/
|
|
95
|
+
export declare function resolveSecretsEnvironment(env?: NextSecretsEnv): SecretsEnvironment | null;
|
|
96
|
+
/**
|
|
97
|
+
* Creates secrets for a Next.js app.
|
|
98
|
+
*
|
|
99
|
+
* It applies the expected-key list for the current deployment environment, and
|
|
100
|
+
* while `next build` prerenders it refuses every operation, including the
|
|
101
|
+
* `tryOpen` variants, with {@link SecretsBuildPhaseError}. A route that uses
|
|
102
|
+
* secrets or calls `assertReady()` must therefore be dynamic.
|
|
103
|
+
*
|
|
104
|
+
* The refusal covers `next build` only. A route that caches its output at run
|
|
105
|
+
* time (`revalidate`, `use cache`) will cache whatever it decrypted.
|
|
106
|
+
*/
|
|
107
|
+
export declare function createNextSecrets(options?: CreateNextSecretsOptions): Secrets;
|
|
108
|
+
//# sourceMappingURL=mod.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../../src/src/next/secrets/mod.ts"],"names":[],"mappings":"AAAA,OAAO,4BAA4B,CAAC;AAEpC,OAAO,EAEL,KAAK,oBAAoB,EAIzB,KAAK,aAAa,EAElB,KAAK,OAAO,EACZ,eAAe,EAEhB,MAAM,sBAAsB,CAAC;AAE9B,cAAc,sBAAsB,CAAC;AAQrC,QAAA,MAAM,YAAY,mDAAoD,CAAC;AAEvE,KAAK,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAEzD,wEAAwE;AACxE,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D,iEAAiE;AACjE,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,CAAC;IACtD,OAAO,CAAC,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,CAAC;CACpD;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACpC;AAED,6CAA6C;AAC7C,MAAM,WAAW,wBACf,SAAQ,IAAI,CAAC,oBAAoB,EAAE,MAAM,GAAG,cAAc,CAAC;IAC3D,oEAAoE;IACpE,IAAI,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,4EAA4E;IAC5E,SAAS,CAAC,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAC7C,YAAY,CAAC,EAAE,uBAAuB,GAAG,SAAS,CAAC;IACnD;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAC7C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAChD;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACvC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACrC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CACzC;AAED;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAe;;CAO1D;AAoBD,4EAA4E;AAC5E,eAAO,MAAM,uBAAuB,6BAA6B,CAAC;AAElE;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,GAAG,GAAE,cAA6B,GACjC,kBAAkB,GAAG,IAAI,CAgB3B;AAiCD;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,GAAE,wBAA6B,GACrC,OAAO,CA2GT"}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
36
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.SECRETS_ENVIRONMENT_ENV = exports.SecretsBuildPhaseError = void 0;
|
|
40
|
+
exports.resolveSecretsEnvironment = resolveSecretsEnvironment;
|
|
41
|
+
exports.createNextSecrets = createNextSecrets;
|
|
42
|
+
require("../../../_dnt.polyfills.js");
|
|
43
|
+
const dntShim = __importStar(require("../../../_dnt.shims.js"));
|
|
44
|
+
const mod_js_1 = require("../../secrets/mod.js");
|
|
45
|
+
__exportStar(require("../../secrets/mod.js"), exports);
|
|
46
|
+
/**
|
|
47
|
+
* The value of `NEXT_PHASE` in the workers that collect page data and
|
|
48
|
+
* prerender during `next build`. Nothing sets it for `next start`, `next dev`
|
|
49
|
+
* or a deployed function.
|
|
50
|
+
*/
|
|
51
|
+
const PRODUCTION_BUILD_PHASE = "phase-production-build";
|
|
52
|
+
const ENVIRONMENTS = ["production", "preview", "development"];
|
|
53
|
+
/**
|
|
54
|
+
* Secrets were used while `next build` was prerendering. Make the route
|
|
55
|
+
* dynamic, so that it runs per request with the deployment's real keys.
|
|
56
|
+
*/
|
|
57
|
+
class SecretsBuildPhaseError extends mod_js_1.SecretsKeyError {
|
|
58
|
+
constructor() {
|
|
59
|
+
super("Secrets are not available while `next build` prerenders. Make the route dynamic.");
|
|
60
|
+
this.name = "SecretsBuildPhaseError";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
exports.SecretsBuildPhaseError = SecretsBuildPhaseError;
|
|
64
|
+
function processEnv() {
|
|
65
|
+
try {
|
|
66
|
+
return dntShim.dntGlobalThis.process
|
|
67
|
+
?.env ?? {};
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// Some runtimes refuse environment access without a permission.
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function read(env, name) {
|
|
75
|
+
try {
|
|
76
|
+
return env[name];
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Names the environment explicitly where `VERCEL_ENV` is not available. */
|
|
83
|
+
exports.SECRETS_ENVIRONMENT_ENV = "LOOM_SECRETS_ENVIRONMENT";
|
|
84
|
+
/**
|
|
85
|
+
* The environment whose expected-key list applies, or `null` when it cannot
|
|
86
|
+
* be told. `LOOM_SECRETS_ENVIRONMENT` wins over `VERCEL_ENV`: set it on hosts
|
|
87
|
+
* other than Vercel, and to `development` in `.env.local` to run a production
|
|
88
|
+
* build locally. When both are set and disagree this still returns the
|
|
89
|
+
* explicit one, but `createNextSecrets` refuses every operation.
|
|
90
|
+
*/
|
|
91
|
+
function resolveSecretsEnvironment(env = processEnv()) {
|
|
92
|
+
const explicit = read(env, exports.SECRETS_ENVIRONMENT_ENV);
|
|
93
|
+
if (explicit !== undefined && explicit !== "") {
|
|
94
|
+
if (!ENVIRONMENTS.includes(explicit)) {
|
|
95
|
+
throw new TypeError(`${exports.SECRETS_ENVIRONMENT_ENV} must be production, preview or development.`);
|
|
96
|
+
}
|
|
97
|
+
return explicit;
|
|
98
|
+
}
|
|
99
|
+
// `NODE_ENV` is "production" in preview builds too, so it cannot tell a
|
|
100
|
+
// preview from production. Vercel's own variable can.
|
|
101
|
+
const vercelEnv = read(env, "VERCEL_ENV");
|
|
102
|
+
return ENVIRONMENTS.includes(vercelEnv)
|
|
103
|
+
? vercelEnv
|
|
104
|
+
: null;
|
|
105
|
+
}
|
|
106
|
+
function recordedList(expectedKeys, environment) {
|
|
107
|
+
const recorded = expectedKeys?.[environment];
|
|
108
|
+
if (recorded === undefined) {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
if (!Array.isArray(recorded)) {
|
|
112
|
+
throw new TypeError(`The ${environment} key list must be an array.`);
|
|
113
|
+
}
|
|
114
|
+
return recorded.length === 0 ? undefined : (0, mod_js_1.parseExpectedSecretKeys)(recorded);
|
|
115
|
+
}
|
|
116
|
+
const GUARDED_METHODS = [
|
|
117
|
+
"seal",
|
|
118
|
+
"sealJson",
|
|
119
|
+
"sealBytes",
|
|
120
|
+
"open",
|
|
121
|
+
"openJson",
|
|
122
|
+
"openBytes",
|
|
123
|
+
"tryOpen",
|
|
124
|
+
"tryOpenJson",
|
|
125
|
+
"tryOpenBytes",
|
|
126
|
+
"needsReseal",
|
|
127
|
+
"reseal",
|
|
128
|
+
"mac",
|
|
129
|
+
"macMatches",
|
|
130
|
+
"macNeedsRefresh",
|
|
131
|
+
];
|
|
132
|
+
/**
|
|
133
|
+
* Creates secrets for a Next.js app.
|
|
134
|
+
*
|
|
135
|
+
* It applies the expected-key list for the current deployment environment, and
|
|
136
|
+
* while `next build` prerenders it refuses every operation, including the
|
|
137
|
+
* `tryOpen` variants, with {@link SecretsBuildPhaseError}. A route that uses
|
|
138
|
+
* secrets or calls `assertReady()` must therefore be dynamic.
|
|
139
|
+
*
|
|
140
|
+
* The refusal covers `next build` only. A route that caches its output at run
|
|
141
|
+
* time (`revalidate`, `use cache`) will cache whatever it decrypted.
|
|
142
|
+
*/
|
|
143
|
+
function createNextSecrets(options = {}) {
|
|
144
|
+
const { allowDuringBuild, allowUnverifiedProduction, environment, expectedKeys, keys, keysEnv, runtimeEnv, variables, ...rest } = options;
|
|
145
|
+
if (environment !== undefined && !ENVIRONMENTS.includes(environment)) {
|
|
146
|
+
throw new TypeError("environment must be production, preview or development.");
|
|
147
|
+
}
|
|
148
|
+
// Both lists are validated now, whatever the current environment, so a
|
|
149
|
+
// malformed production list fails a local build instead of the first
|
|
150
|
+
// production request.
|
|
151
|
+
const lists = {
|
|
152
|
+
production: recordedList(expectedKeys, "production"),
|
|
153
|
+
preview: recordedList(expectedKeys, "preview"),
|
|
154
|
+
};
|
|
155
|
+
const runtime = () => runtimeEnv ?? processEnv();
|
|
156
|
+
const resolved = environment ?? resolveSecretsEnvironment(runtime());
|
|
157
|
+
const applied = resolved === "production" || resolved === "preview"
|
|
158
|
+
? lists[resolved]
|
|
159
|
+
: undefined;
|
|
160
|
+
/** Throws when secrets must not be used right now. */
|
|
161
|
+
function guard() {
|
|
162
|
+
if (!allowDuringBuild &&
|
|
163
|
+
read(runtime(), "NEXT_PHASE") === PRODUCTION_BUILD_PHASE) {
|
|
164
|
+
throw new SecretsBuildPhaseError();
|
|
165
|
+
}
|
|
166
|
+
// An explicit variable that contradicts the platform's own would quietly
|
|
167
|
+
// drop the platform's key list (`development` on a production deployment,
|
|
168
|
+
// for example from a `.env.local` that reached the image), so neither is
|
|
169
|
+
// trusted. An `environment` option is the app's own decision and is not
|
|
170
|
+
// second-guessed.
|
|
171
|
+
if (environment === undefined) {
|
|
172
|
+
const explicit = read(runtime(), exports.SECRETS_ENVIRONMENT_ENV);
|
|
173
|
+
const vercelEnv = read(runtime(), "VERCEL_ENV");
|
|
174
|
+
if (ENVIRONMENTS.includes(explicit) &&
|
|
175
|
+
ENVIRONMENTS.includes(vercelEnv) &&
|
|
176
|
+
explicit !== vercelEnv) {
|
|
177
|
+
throw new mod_js_1.SecretsKeyError(`${exports.SECRETS_ENVIRONMENT_ENV} is ${explicit} but VERCEL_ENV is ${vercelEnv}. Secrets are refused until the two name the same environment.`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// Lists are recorded, but nothing says which environment this is while
|
|
181
|
+
// the process claims to be production: ignoring them here would look
|
|
182
|
+
// exactly like a healthy, verified deployment.
|
|
183
|
+
if (resolved === null &&
|
|
184
|
+
read(runtime(), "NODE_ENV") === "production" &&
|
|
185
|
+
(lists.production !== undefined || lists.preview !== undefined)) {
|
|
186
|
+
throw new mod_js_1.SecretsKeyError(`Key fingerprints are recorded but the deployment environment is unknown. Set ${exports.SECRETS_ENVIRONMENT_ENV} to production, preview or development.`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const inner = (0, mod_js_1.createSecrets)({
|
|
190
|
+
...rest,
|
|
191
|
+
expectedKeys: applied,
|
|
192
|
+
keys: keys ?? (0, mod_js_1.envKeyring)({ ...variables, env: keysEnv }),
|
|
193
|
+
});
|
|
194
|
+
async function assertReady() {
|
|
195
|
+
guard();
|
|
196
|
+
const readiness = await inner.assertReady();
|
|
197
|
+
if (resolved === "production" && !readiness.verified &&
|
|
198
|
+
!allowUnverifiedProduction) {
|
|
199
|
+
throw new mod_js_1.SecretsKeyError("No production key list is recorded, so the deployed key cannot be verified. Record its fingerprint in loom.json.");
|
|
200
|
+
}
|
|
201
|
+
return readiness;
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
assertReady,
|
|
205
|
+
purpose(name, purposeOptions) {
|
|
206
|
+
const purpose = inner.purpose(name, purposeOptions);
|
|
207
|
+
const guarded = {};
|
|
208
|
+
for (const method of GUARDED_METHODS) {
|
|
209
|
+
// deno-lint-ignore require-await -- async so the guard rejects.
|
|
210
|
+
guarded[method] = async (...args) => {
|
|
211
|
+
guard();
|
|
212
|
+
return purpose[method](...args);
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
return { ...purpose, ...guarded, assertReady };
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rejects strings that UTF-8 encoding would silently change.
|
|
3
|
+
*
|
|
4
|
+
* `TextEncoder` turns every lone surrogate into U+FFFD, so two different
|
|
5
|
+
* JavaScript strings could otherwise produce the same bytes and collide as
|
|
6
|
+
* bindings or fingerprint input.
|
|
7
|
+
*/
|
|
8
|
+
export declare function assertWellFormed(value: string, what: string): string;
|
|
9
|
+
/** UTF-8 bytes of a well-formed string. */
|
|
10
|
+
export declare function encodeUtf8(value: string, what: string): Uint8Array<ArrayBuffer>;
|
|
11
|
+
/** Strict UTF-8 decoding. Throws on malformed input; preserves a leading BOM. */
|
|
12
|
+
export declare function decodeUtf8(bytes: Uint8Array): string;
|
|
13
|
+
/** Unpadded base64url. */
|
|
14
|
+
export declare function toBase64Url(bytes: Uint8Array): string;
|
|
15
|
+
/**
|
|
16
|
+
* Decodes unpadded base64url, accepting only the canonical spelling.
|
|
17
|
+
*
|
|
18
|
+
* Decoders tolerate padding, the standard alphabet and non-zero trailing bits.
|
|
19
|
+
* Re-encoding and comparing leaves exactly one accepted string per byte
|
|
20
|
+
* sequence, so a stored ciphertext cannot be respelled.
|
|
21
|
+
*/
|
|
22
|
+
export declare function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null;
|
|
23
|
+
/**
|
|
24
|
+
* Pre-authentication encoding, as in PASETO: a little-endian 64-bit count of
|
|
25
|
+
* pieces, then each piece prefixed with its little-endian 64-bit byte length.
|
|
26
|
+
*
|
|
27
|
+
* Joining fields with a separator is ambiguous whenever a field can contain
|
|
28
|
+
* the separator. Length prefixes make the encoding injective, so no two
|
|
29
|
+
* different lists of pieces produce the same bytes.
|
|
30
|
+
*/
|
|
31
|
+
export declare function pae(pieces: readonly (string | Uint8Array)[]): Uint8Array<ArrayBuffer>;
|
|
32
|
+
//# sourceMappingURL=encoding.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/encoding.ts"],"names":[],"mappings":"AAQA;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAQpE;AAED,2CAA2C;AAC3C,wBAAgB,UAAU,CACxB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,GACX,UAAU,CAAC,WAAW,CAAC,CAEzB;AAED,iFAAiF;AACjF,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEpD;AAED,0BAA0B;AAC1B,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAWrD;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,GAAG,IAAI,CAe1E;AAED;;;;;;;GAOG;AACH,wBAAgB,GAAG,CACjB,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,UAAU,CAAC,EAAE,GACvC,UAAU,CAAC,WAAW,CAAC,CAezB"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertWellFormed = assertWellFormed;
|
|
4
|
+
exports.encodeUtf8 = encodeUtf8;
|
|
5
|
+
exports.decodeUtf8 = decodeUtf8;
|
|
6
|
+
exports.toBase64Url = toBase64Url;
|
|
7
|
+
exports.fromBase64Url = fromBase64Url;
|
|
8
|
+
exports.pae = pae;
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
// `ignoreBOM: true` keeps a leading U+FEFF in the output; the default strips it.
|
|
11
|
+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
12
|
+
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]*$/;
|
|
13
|
+
// Stay well under engine argument limits when spreading into fromCharCode.
|
|
14
|
+
const BINARY_CHUNK = 0x8000;
|
|
15
|
+
/**
|
|
16
|
+
* Rejects strings that UTF-8 encoding would silently change.
|
|
17
|
+
*
|
|
18
|
+
* `TextEncoder` turns every lone surrogate into U+FFFD, so two different
|
|
19
|
+
* JavaScript strings could otherwise produce the same bytes and collide as
|
|
20
|
+
* bindings or fingerprint input.
|
|
21
|
+
*/
|
|
22
|
+
function assertWellFormed(value, what) {
|
|
23
|
+
if (typeof value !== "string") {
|
|
24
|
+
throw new TypeError(`${what} must be a string.`);
|
|
25
|
+
}
|
|
26
|
+
if (!value.isWellFormed()) {
|
|
27
|
+
throw new TypeError(`${what} must be well-formed Unicode.`);
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
/** UTF-8 bytes of a well-formed string. */
|
|
32
|
+
function encodeUtf8(value, what) {
|
|
33
|
+
return encoder.encode(assertWellFormed(value, what));
|
|
34
|
+
}
|
|
35
|
+
/** Strict UTF-8 decoding. Throws on malformed input; preserves a leading BOM. */
|
|
36
|
+
function decodeUtf8(bytes) {
|
|
37
|
+
return decoder.decode(bytes);
|
|
38
|
+
}
|
|
39
|
+
/** Unpadded base64url. */
|
|
40
|
+
function toBase64Url(bytes) {
|
|
41
|
+
let binary = "";
|
|
42
|
+
for (let offset = 0; offset < bytes.length; offset += BINARY_CHUNK) {
|
|
43
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + BINARY_CHUNK));
|
|
44
|
+
}
|
|
45
|
+
return btoa(binary)
|
|
46
|
+
.replaceAll("+", "-")
|
|
47
|
+
.replaceAll("/", "_")
|
|
48
|
+
.replace(/=+$/, "");
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Decodes unpadded base64url, accepting only the canonical spelling.
|
|
52
|
+
*
|
|
53
|
+
* Decoders tolerate padding, the standard alphabet and non-zero trailing bits.
|
|
54
|
+
* Re-encoding and comparing leaves exactly one accepted string per byte
|
|
55
|
+
* sequence, so a stored ciphertext cannot be respelled.
|
|
56
|
+
*/
|
|
57
|
+
function fromBase64Url(text) {
|
|
58
|
+
if (!BASE64URL_PATTERN.test(text)) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
let binary;
|
|
62
|
+
try {
|
|
63
|
+
binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const bytes = new Uint8Array(binary.length);
|
|
69
|
+
for (let index = 0; index < binary.length; index += 1) {
|
|
70
|
+
bytes[index] = binary.charCodeAt(index);
|
|
71
|
+
}
|
|
72
|
+
return toBase64Url(bytes) === text ? bytes : null;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Pre-authentication encoding, as in PASETO: a little-endian 64-bit count of
|
|
76
|
+
* pieces, then each piece prefixed with its little-endian 64-bit byte length.
|
|
77
|
+
*
|
|
78
|
+
* Joining fields with a separator is ambiguous whenever a field can contain
|
|
79
|
+
* the separator. Length prefixes make the encoding injective, so no two
|
|
80
|
+
* different lists of pieces produce the same bytes.
|
|
81
|
+
*/
|
|
82
|
+
function pae(pieces) {
|
|
83
|
+
const encoded = pieces.map((piece) => piece instanceof Uint8Array ? piece : encodeUtf8(piece, "Encoded piece"));
|
|
84
|
+
const length = encoded.reduce((total, piece) => total + 8 + piece.length, 8);
|
|
85
|
+
const output = new Uint8Array(length);
|
|
86
|
+
const view = new DataView(output.buffer);
|
|
87
|
+
view.setBigUint64(0, BigInt(encoded.length), true);
|
|
88
|
+
let offset = 8;
|
|
89
|
+
for (const piece of encoded) {
|
|
90
|
+
view.setBigUint64(offset, BigInt(piece.length), true);
|
|
91
|
+
output.set(piece, offset + 8);
|
|
92
|
+
offset += 8 + piece.length;
|
|
93
|
+
}
|
|
94
|
+
return output;
|
|
95
|
+
}
|