@myfield/sdk 0.9.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 +19 -0
- package/LICENSE +201 -0
- package/README.md +125 -0
- package/dist/index.js +2254 -0
- package/docs/API.md +210 -0
- package/docs/BUCKET-SPEC.md +153 -0
- package/package.json +58 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/instance.ts +876 -0
- package/src/bucket/binary.ts +253 -0
- package/src/bucket/client.ts +383 -0
- package/src/bucket/crypto.ts +58 -0
- package/src/bucket/format.ts +275 -0
- package/src/bucket/index.ts +40 -0
- package/src/bucket/keys.ts +104 -0
- package/src/bucket/store.ts +159 -0
- package/src/bucket/transport.ts +187 -0
- package/src/errors.ts +9 -0
- package/src/facade.ts +691 -0
- package/src/index.ts +23 -0
- package/src/internal/encoding.ts +95 -0
- package/types/index.d.ts +70 -0
|
@@ -0,0 +1,876 @@
|
|
|
1
|
+
// Instance auth client for the open surface, ported from the notepad
|
|
2
|
+
// prototype and trimmed to the open contract:
|
|
3
|
+
// - bucket resources only, fixed read+write capabilities
|
|
4
|
+
// - SDK v1 authorization (`mf_auth_mode=v1` is always sent); the
|
|
5
|
+
// app-visible mfid is a pairwise alias, never the owner mfid
|
|
6
|
+
// - exactly two API routes: instance-challenge and instance-session
|
|
7
|
+
// (alias mode has no grant refetch; bucket access rides on the
|
|
8
|
+
// callback-provided bucketAccessGrant)
|
|
9
|
+
// The /auth fragment wire format is frozen as-is, including its vestigial
|
|
10
|
+
// OAuth-shaped fields; this module hides it from apps entirely.
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
b64urlToBytes,
|
|
14
|
+
bytesToB64url,
|
|
15
|
+
bytesToHex,
|
|
16
|
+
normalizeIsoDateTime,
|
|
17
|
+
randomId,
|
|
18
|
+
sha256Hex,
|
|
19
|
+
stableStringify,
|
|
20
|
+
utf8Encode,
|
|
21
|
+
} from "../internal/encoding.ts";
|
|
22
|
+
import { unwrapBucketKeys, type BucketKeyGrantEnvelope, type BucketKeys } from "../bucket/keys.ts";
|
|
23
|
+
import { createIndexedDbStorageAdapter, type StorageAdapter } from "../bucket/store.ts";
|
|
24
|
+
|
|
25
|
+
export type AuthCapability = "read" | "write";
|
|
26
|
+
|
|
27
|
+
export type AuthInstance = {
|
|
28
|
+
v: 1;
|
|
29
|
+
instanceId: string;
|
|
30
|
+
signingPublicJwk: JsonWebKey;
|
|
31
|
+
signingPrivateKey: CryptoKey;
|
|
32
|
+
wrappingPublicJwk: JsonWebKey;
|
|
33
|
+
wrappingPrivateKey: CryptoKey;
|
|
34
|
+
createdAt: string;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type InstanceAuthContext = {
|
|
38
|
+
v: 1;
|
|
39
|
+
mfid: string;
|
|
40
|
+
resourceId: string;
|
|
41
|
+
remoteResourceId?: string;
|
|
42
|
+
resourceApiUrl?: string;
|
|
43
|
+
instanceId: string;
|
|
44
|
+
requestId: string;
|
|
45
|
+
authorizedAt: string;
|
|
46
|
+
bucketAccessGrant?: BucketAccessGrant;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type CloudSessionCredential =
|
|
50
|
+
| { carrier: "bearer"; token: string; expiresAt: string }
|
|
51
|
+
| { carrier: "cookie"; expiresAt: string };
|
|
52
|
+
|
|
53
|
+
export type BucketAccess = {
|
|
54
|
+
mfid: string;
|
|
55
|
+
instanceId: string;
|
|
56
|
+
bucketId: string;
|
|
57
|
+
resourceId: string;
|
|
58
|
+
resourceApiUrl?: string;
|
|
59
|
+
capabilities: AuthCapability[];
|
|
60
|
+
grantRecordId: string;
|
|
61
|
+
keys: BucketKeys;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export type InstanceAuthClientOptions = {
|
|
65
|
+
appId?: string;
|
|
66
|
+
apiBase?: string;
|
|
67
|
+
authPageUrl?: string;
|
|
68
|
+
redirectUri?: string;
|
|
69
|
+
origin?: string;
|
|
70
|
+
openAuthUrl?: (url: string) => void | Promise<void>;
|
|
71
|
+
storage?: StorageAdapter;
|
|
72
|
+
fetchImpl?: typeof fetch;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export type AuthCallbackResult = {
|
|
76
|
+
requestId: string;
|
|
77
|
+
state: string;
|
|
78
|
+
result: "approved" | "denied" | "error";
|
|
79
|
+
resourceId?: string;
|
|
80
|
+
error?: string;
|
|
81
|
+
errorDescription?: string;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export type InstanceAuthClient = {
|
|
85
|
+
ensureInstance(): Promise<AuthInstance>;
|
|
86
|
+
authorize(request: { bucketId: string }): Promise<void>;
|
|
87
|
+
handleCallback(url?: string): Promise<AuthCallbackResult | null>;
|
|
88
|
+
getContext(bucketId: string): Promise<InstanceAuthContext | null>;
|
|
89
|
+
getSession(bucketId: string, options?: { forceRefresh?: boolean }): Promise<CloudSessionCredential>;
|
|
90
|
+
getBucketAccess(bucketId: string): Promise<BucketAccess>;
|
|
91
|
+
clearContext(bucketId: string): Promise<void>;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export type BucketAccessGrant = {
|
|
95
|
+
v: 1;
|
|
96
|
+
grantRecordId: string;
|
|
97
|
+
mfid: string;
|
|
98
|
+
resourceId: string;
|
|
99
|
+
instanceId: string;
|
|
100
|
+
issuedAt: string;
|
|
101
|
+
keyId: string;
|
|
102
|
+
capabilities: AuthCapability[];
|
|
103
|
+
envelope: BucketKeyGrantEnvelope;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
type StoredAuthAuthorizationResult = {
|
|
107
|
+
v: 1;
|
|
108
|
+
requestId: string;
|
|
109
|
+
state: string;
|
|
110
|
+
result: "approved";
|
|
111
|
+
mfid: string;
|
|
112
|
+
resourceId: string;
|
|
113
|
+
instanceId: string;
|
|
114
|
+
createdAt: string;
|
|
115
|
+
resourceApiUrl?: string;
|
|
116
|
+
bucketAccessGrant?: BucketAccessGrant;
|
|
117
|
+
expiresAt?: string;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
type EncryptedAuthAuthorizationResultEnvelope = {
|
|
121
|
+
v: 1;
|
|
122
|
+
typ: "auth.authorization-result.envelope.v1";
|
|
123
|
+
alg: "ECDH-HKDF-SHA-256/AES-GCM-256";
|
|
124
|
+
requestId: string;
|
|
125
|
+
state: string;
|
|
126
|
+
resourceId: string;
|
|
127
|
+
instanceId: string;
|
|
128
|
+
ephemeralPublicJwk: JsonWebKey;
|
|
129
|
+
salt: string;
|
|
130
|
+
iv: string;
|
|
131
|
+
aad: string;
|
|
132
|
+
ciphertext: string;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
type PendingInstanceAuthRequest = {
|
|
136
|
+
v: 1;
|
|
137
|
+
requestId: string;
|
|
138
|
+
state: string;
|
|
139
|
+
resourceId: string;
|
|
140
|
+
capabilities: AuthCapability[];
|
|
141
|
+
instanceId: string;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
type InstanceAuthCallbackPointer = {
|
|
145
|
+
v: 1;
|
|
146
|
+
requestId: string;
|
|
147
|
+
resourceId: string;
|
|
148
|
+
instanceId: string;
|
|
149
|
+
pendingKey: string;
|
|
150
|
+
createdAt: string;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
type StoredAuthInstance = AuthInstance & { updatedAt: string };
|
|
154
|
+
type ActiveInstancePointer = { v: 1; instanceId: string; updatedAt: string };
|
|
155
|
+
|
|
156
|
+
type StoredCloudSessionCredential = {
|
|
157
|
+
v: 1;
|
|
158
|
+
mfid: string;
|
|
159
|
+
resourceId: string;
|
|
160
|
+
instanceId: string;
|
|
161
|
+
credential: CloudSessionCredential;
|
|
162
|
+
storedAt?: string;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
type InstanceProof = {
|
|
166
|
+
type: "instance.es256";
|
|
167
|
+
instanceId: string;
|
|
168
|
+
alg: "ES256";
|
|
169
|
+
signedAt: string;
|
|
170
|
+
signature: string;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const AUTH_REQUEST_TTL_MS = 10 * 60 * 1000;
|
|
174
|
+
const AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
|
|
175
|
+
const DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
|
|
176
|
+
const BUCKET_ACCESS_CACHE_TTL_MS = 60_000;
|
|
177
|
+
const INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1000;
|
|
178
|
+
const INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1000;
|
|
179
|
+
const FIXED_CAPABILITIES: AuthCapability[] = ["read", "write"];
|
|
180
|
+
|
|
181
|
+
export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}): InstanceAuthClient {
|
|
182
|
+
let instance: AuthInstance | null = null;
|
|
183
|
+
const appId = normalizeInstanceAppId(options.appId);
|
|
184
|
+
let mfid = "";
|
|
185
|
+
let currentResourceId = "";
|
|
186
|
+
let currentSession: { resourceId: string; credential: CloudSessionCredential } | null = null;
|
|
187
|
+
const inFlightSessionRefreshes = new Map<string, Promise<CloudSessionCredential>>();
|
|
188
|
+
const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
|
|
189
|
+
const fetchImpl = options.fetchImpl || fetch;
|
|
190
|
+
const bucketAccessCache = new Map<string, { access: BucketAccess; expiresAt: number }>();
|
|
191
|
+
|
|
192
|
+
const activeInstanceKey = () => `instance:${seg(appId)}:active-instance:current`;
|
|
193
|
+
const instanceKey = (instanceId: string) => `instance:${seg(appId)}:instance-key:${seg(instanceId)}`;
|
|
194
|
+
const pendingAuthKey = (resourceId: string, instanceId: string) => `instance:${seg(appId)}:pending-auth:${seg(resourceId)}:${seg(instanceId)}`;
|
|
195
|
+
const callbackPointerKey = (requestId: string) => `instance:${seg(appId)}:callback-pointer:${seg(requestId)}`;
|
|
196
|
+
const contextKey = (resourceId: string, instanceId: string) => `instance:${seg(appId)}:context:${seg(resourceId)}:${seg(instanceId)}`;
|
|
197
|
+
const sessionKey = (resourceId: string, instanceId: string) => `instance:${seg(appId)}:session:${seg(resourceId)}:${seg(instanceId)}`;
|
|
198
|
+
|
|
199
|
+
function isStoredAuthInstance(value: StoredAuthInstance | null, instanceId?: string): value is StoredAuthInstance {
|
|
200
|
+
return (
|
|
201
|
+
!!value &&
|
|
202
|
+
value.v === 1 &&
|
|
203
|
+
isValidInstanceId(value.instanceId) &&
|
|
204
|
+
(!instanceId || value.instanceId === instanceId) &&
|
|
205
|
+
value.signingPrivateKey instanceof CryptoKey &&
|
|
206
|
+
value.wrappingPrivateKey instanceof CryptoKey
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function readStoredInstance(instanceId: string): Promise<StoredAuthInstance | null> {
|
|
211
|
+
const stored = await storage.get<StoredAuthInstance>(instanceKey(instanceId));
|
|
212
|
+
return isStoredAuthInstance(stored, instanceId) ? stored : null;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function writeStoredInstance(authInstance: AuthInstance): Promise<StoredAuthInstance> {
|
|
216
|
+
const existing = await readStoredInstance(authInstance.instanceId);
|
|
217
|
+
const stored: StoredAuthInstance = {
|
|
218
|
+
...authInstance,
|
|
219
|
+
updatedAt: new Date().toISOString(),
|
|
220
|
+
createdAt: authInstance.createdAt || existing?.createdAt || new Date().toISOString(),
|
|
221
|
+
};
|
|
222
|
+
await storage.set(instanceKey(authInstance.instanceId), stored);
|
|
223
|
+
const verified = await readStoredInstance(authInstance.instanceId);
|
|
224
|
+
if (!verified) throw new Error("auth instance write did not persist keys");
|
|
225
|
+
await storage.set(activeInstanceKey(), { v: 1, instanceId: authInstance.instanceId, updatedAt: new Date().toISOString() } satisfies ActiveInstancePointer);
|
|
226
|
+
instance = verified;
|
|
227
|
+
return verified;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function readActiveStoredInstance(): Promise<StoredAuthInstance | null> {
|
|
231
|
+
const active = await storage.get<ActiveInstancePointer>(activeInstanceKey());
|
|
232
|
+
if (!active || active.v !== 1 || !isValidInstanceId(active.instanceId)) return null;
|
|
233
|
+
return readStoredInstance(active.instanceId);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function ensureStoredInstance(): Promise<StoredAuthInstance> {
|
|
237
|
+
if (instance) {
|
|
238
|
+
const stored = await readStoredInstance(instance.instanceId);
|
|
239
|
+
if (stored) return stored;
|
|
240
|
+
return writeStoredInstance(instance);
|
|
241
|
+
}
|
|
242
|
+
const active = await readActiveStoredInstance();
|
|
243
|
+
if (active) {
|
|
244
|
+
instance = active;
|
|
245
|
+
return active;
|
|
246
|
+
}
|
|
247
|
+
return writeStoredInstance(await generateAuthInstance());
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function readContext(resourceId: string): Promise<InstanceAuthContext | null> {
|
|
251
|
+
if (!parseBucketResourceId(resourceId)) return null;
|
|
252
|
+
const authInstance = await readActiveStoredInstance();
|
|
253
|
+
if (!authInstance) return null;
|
|
254
|
+
const context = await storage.get<InstanceAuthContext>(contextKey(resourceId, authInstance.instanceId));
|
|
255
|
+
if (
|
|
256
|
+
!context ||
|
|
257
|
+
context.v !== 1 ||
|
|
258
|
+
!isValidMfid(context.mfid) ||
|
|
259
|
+
context.resourceId !== resourceId ||
|
|
260
|
+
(context.remoteResourceId !== undefined && !parseBucketResourceId(context.remoteResourceId)) ||
|
|
261
|
+
context.instanceId !== authInstance.instanceId
|
|
262
|
+
) {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
mfid = context.mfid;
|
|
266
|
+
currentResourceId = context.resourceId;
|
|
267
|
+
instance = authInstance;
|
|
268
|
+
return context;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function getSessionForResource(resourceId: string, sessionOptions?: { forceRefresh?: boolean }): Promise<CloudSessionCredential> {
|
|
272
|
+
const context = await readContext(resourceId);
|
|
273
|
+
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
274
|
+
const authInstance = await ensureStoredInstance();
|
|
275
|
+
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
276
|
+
const sessionResourceId = context.remoteResourceId || context.resourceId;
|
|
277
|
+
const forceRefresh = sessionOptions?.forceRefresh === true;
|
|
278
|
+
const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
|
|
279
|
+
|
|
280
|
+
const performRefreshSession = async (): Promise<CloudSessionCredential> => {
|
|
281
|
+
const challenge = await postJson<{ challengeId: string; challenge: string }>(fetchImpl, options.apiBase, "/v1/api/auth/instance-challenge", {
|
|
282
|
+
mfid,
|
|
283
|
+
resourceId: sessionResourceId,
|
|
284
|
+
instanceId: authInstance.instanceId,
|
|
285
|
+
});
|
|
286
|
+
const proof = await signInstanceChallenge({
|
|
287
|
+
instance: authInstance,
|
|
288
|
+
challengeId: challenge.challengeId,
|
|
289
|
+
challenge: challenge.challenge,
|
|
290
|
+
mfid,
|
|
291
|
+
resourceId: sessionResourceId,
|
|
292
|
+
});
|
|
293
|
+
const session = await postJson<{ credential: CloudSessionCredential }>(fetchImpl, options.apiBase, "/v1/api/auth/instance-session", {
|
|
294
|
+
mfid,
|
|
295
|
+
resourceId: sessionResourceId,
|
|
296
|
+
instanceId: authInstance.instanceId,
|
|
297
|
+
challengeId: challenge.challengeId,
|
|
298
|
+
proof,
|
|
299
|
+
credentialCarrier: "bearer",
|
|
300
|
+
});
|
|
301
|
+
currentSession = { resourceId: sessionResourceId, credential: session.credential };
|
|
302
|
+
if (session.credential.carrier === "bearer") {
|
|
303
|
+
await storage.set(sessionKey(sessionResourceId, context.instanceId), {
|
|
304
|
+
v: 1,
|
|
305
|
+
mfid,
|
|
306
|
+
resourceId: sessionResourceId,
|
|
307
|
+
instanceId: authInstance.instanceId,
|
|
308
|
+
credential: session.credential,
|
|
309
|
+
storedAt: new Date().toISOString(),
|
|
310
|
+
} satisfies StoredCloudSessionCredential);
|
|
311
|
+
}
|
|
312
|
+
return session.credential;
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
const refreshSession = (): Promise<CloudSessionCredential> => {
|
|
316
|
+
const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
|
|
317
|
+
if (inFlight) return inFlight;
|
|
318
|
+
const promise = performRefreshSession().finally(() => {
|
|
319
|
+
if (inFlightSessionRefreshes.get(refreshSessionKey) === promise) inFlightSessionRefreshes.delete(refreshSessionKey);
|
|
320
|
+
});
|
|
321
|
+
inFlightSessionRefreshes.set(refreshSessionKey, promise);
|
|
322
|
+
return promise;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
if (!forceRefresh) {
|
|
326
|
+
let cachedCredential: CloudSessionCredential | null = null;
|
|
327
|
+
if (currentSession?.resourceId === sessionResourceId && isSessionUsable(currentSession.credential)) {
|
|
328
|
+
cachedCredential = currentSession.credential;
|
|
329
|
+
} else {
|
|
330
|
+
const stored = await storage.get<StoredCloudSessionCredential>(sessionKey(sessionResourceId, context.instanceId));
|
|
331
|
+
if (
|
|
332
|
+
stored?.v === 1 &&
|
|
333
|
+
stored.mfid === mfid &&
|
|
334
|
+
stored.resourceId === sessionResourceId &&
|
|
335
|
+
stored.instanceId === authInstance.instanceId &&
|
|
336
|
+
isSessionUsable(stored.credential)
|
|
337
|
+
) {
|
|
338
|
+
currentSession = { resourceId: sessionResourceId, credential: stored.credential };
|
|
339
|
+
cachedCredential = stored.credential;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (cachedCredential) {
|
|
343
|
+
if (shouldBestEffortRefreshSession(cachedCredential)) void refreshSession().catch(() => undefined);
|
|
344
|
+
return cachedCredential;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (forceRefresh) inFlightSessionRefreshes.delete(refreshSessionKey);
|
|
349
|
+
return refreshSession();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return {
|
|
353
|
+
async ensureInstance() {
|
|
354
|
+
return ensureStoredInstance();
|
|
355
|
+
},
|
|
356
|
+
async authorize(request) {
|
|
357
|
+
const resourceId = bucketResourceId(requireValidBucketId(request.bucketId));
|
|
358
|
+
const authInstance = await ensureStoredInstance();
|
|
359
|
+
currentResourceId = resourceId;
|
|
360
|
+
const state = randomId("state");
|
|
361
|
+
const requestId = randomId("req");
|
|
362
|
+
const nextPendingKey = pendingAuthKey(resourceId, authInstance.instanceId);
|
|
363
|
+
const fragment = buildAuthRequestFragment({
|
|
364
|
+
clientId: appId,
|
|
365
|
+
requestId,
|
|
366
|
+
state,
|
|
367
|
+
redirectUri: options.redirectUri || browserLocationHref(),
|
|
368
|
+
origin: options.origin || browserLocationOrigin(),
|
|
369
|
+
resourceId,
|
|
370
|
+
capabilities: FIXED_CAPABILITIES,
|
|
371
|
+
instanceId: authInstance.instanceId,
|
|
372
|
+
instanceSigningPublicJwk: authInstance.signingPublicJwk,
|
|
373
|
+
instanceWrappingPublicJwk: authInstance.wrappingPublicJwk,
|
|
374
|
+
createdAt: new Date().toISOString(),
|
|
375
|
+
});
|
|
376
|
+
await storage.set(nextPendingKey, {
|
|
377
|
+
v: 1,
|
|
378
|
+
requestId,
|
|
379
|
+
state,
|
|
380
|
+
resourceId,
|
|
381
|
+
capabilities: FIXED_CAPABILITIES,
|
|
382
|
+
instanceId: authInstance.instanceId,
|
|
383
|
+
} satisfies PendingInstanceAuthRequest);
|
|
384
|
+
await storage.set(callbackPointerKey(requestId), {
|
|
385
|
+
v: 1,
|
|
386
|
+
requestId,
|
|
387
|
+
resourceId,
|
|
388
|
+
instanceId: authInstance.instanceId,
|
|
389
|
+
pendingKey: nextPendingKey,
|
|
390
|
+
createdAt: new Date().toISOString(),
|
|
391
|
+
} satisfies InstanceAuthCallbackPointer);
|
|
392
|
+
const authPageUrl = String(options.authPageUrl || "").trim();
|
|
393
|
+
if (!authPageUrl) throw new Error("authPageUrl is required to authorize an instance");
|
|
394
|
+
const authUrl = `${authPageUrl}${fragment}`;
|
|
395
|
+
if (options.openAuthUrl) {
|
|
396
|
+
await options.openAuthUrl(authUrl);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (typeof window === "undefined") throw new Error("browser window required for authorize redirect");
|
|
400
|
+
window.location.href = authUrl;
|
|
401
|
+
},
|
|
402
|
+
async handleCallback(url) {
|
|
403
|
+
const parsed = url && /^[a-z][a-z0-9+.-]*:/i.test(url) ? new URL(url) : new URL(url || browserLocationHref(), browserLocationOrigin());
|
|
404
|
+
let encryptedEnvelope: EncryptedAuthAuthorizationResultEnvelope | null = null;
|
|
405
|
+
let encryptedEnvelopeInvalid = false;
|
|
406
|
+
try {
|
|
407
|
+
encryptedEnvelope = parseEncryptedAuthAuthorizationResultFragment(parsed.hash);
|
|
408
|
+
} catch {
|
|
409
|
+
encryptedEnvelopeInvalid = true;
|
|
410
|
+
}
|
|
411
|
+
const result: AuthCallbackResult = {
|
|
412
|
+
requestId: parsed.searchParams.get("mf_request_id") || "",
|
|
413
|
+
state: parsed.searchParams.get("state") || "",
|
|
414
|
+
result: (parsed.searchParams.get("mf_result") || (parsed.searchParams.get("error") ? "error" : "")) as AuthCallbackResult["result"],
|
|
415
|
+
...(parsed.searchParams.get("error") ? { error: parsed.searchParams.get("error") || undefined } : {}),
|
|
416
|
+
...(parsed.searchParams.get("error_description") ? { errorDescription: parsed.searchParams.get("error_description") || undefined } : {}),
|
|
417
|
+
};
|
|
418
|
+
if (!result.requestId || !result.state || !["approved", "denied", "error"].includes(result.result)) return null;
|
|
419
|
+
const pointer = await storage.get<InstanceAuthCallbackPointer>(callbackPointerKey(result.requestId));
|
|
420
|
+
if (!pointer || pointer.v !== 1 || pointer.requestId !== result.requestId || !isFresh(pointer.createdAt)) return null;
|
|
421
|
+
const expected = await storage.get<PendingInstanceAuthRequest>(pointer.pendingKey);
|
|
422
|
+
if (!expected || expected.v !== 1 || expected.requestId !== result.requestId || expected.state !== result.state) return null;
|
|
423
|
+
result.resourceId = expected.resourceId;
|
|
424
|
+
if (result.result === "approved") {
|
|
425
|
+
if (encryptedEnvelopeInvalid || !encryptedEnvelope) {
|
|
426
|
+
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_result_invalid" };
|
|
427
|
+
}
|
|
428
|
+
const authInstance = await readStoredInstance(expected.instanceId);
|
|
429
|
+
if (!authInstance) return { ...result, result: "error", error: "server_error", errorDescription: "authorization_instance_missing" };
|
|
430
|
+
let stored: StoredAuthAuthorizationResult;
|
|
431
|
+
try {
|
|
432
|
+
stored = await decryptEncryptedAuthAuthorizationResult({
|
|
433
|
+
envelope: encryptedEnvelope,
|
|
434
|
+
instanceWrappingPrivateKey: authInstance.wrappingPrivateKey,
|
|
435
|
+
expectedRequestId: result.requestId,
|
|
436
|
+
expectedState: result.state,
|
|
437
|
+
expectedResourceId: expected.resourceId,
|
|
438
|
+
expectedInstanceId: expected.instanceId,
|
|
439
|
+
});
|
|
440
|
+
} catch {
|
|
441
|
+
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_result_invalid" };
|
|
442
|
+
}
|
|
443
|
+
if (stored.resourceId !== pointer.resourceId || stored.instanceId !== pointer.instanceId) {
|
|
444
|
+
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_context_mismatch" };
|
|
445
|
+
}
|
|
446
|
+
const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
|
|
447
|
+
mfid = stored.mfid;
|
|
448
|
+
currentResourceId = stored.resourceId;
|
|
449
|
+
await storage.set(contextKey(stored.resourceId, stored.instanceId), {
|
|
450
|
+
v: 1,
|
|
451
|
+
mfid: stored.mfid,
|
|
452
|
+
resourceId: stored.resourceId,
|
|
453
|
+
...(remoteResourceId !== stored.resourceId ? { remoteResourceId } : {}),
|
|
454
|
+
...(stored.resourceApiUrl ? { resourceApiUrl: stored.resourceApiUrl } : {}),
|
|
455
|
+
instanceId: stored.instanceId,
|
|
456
|
+
requestId: result.requestId,
|
|
457
|
+
authorizedAt: new Date().toISOString(),
|
|
458
|
+
...(stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}),
|
|
459
|
+
} satisfies InstanceAuthContext);
|
|
460
|
+
await writeStoredInstance(authInstance);
|
|
461
|
+
if (currentSession?.resourceId === remoteResourceId) currentSession = null;
|
|
462
|
+
await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
|
|
463
|
+
bucketAccessCache.clear();
|
|
464
|
+
}
|
|
465
|
+
await storage.remove(pointer.pendingKey);
|
|
466
|
+
await storage.remove(callbackPointerKey(result.requestId));
|
|
467
|
+
return result;
|
|
468
|
+
},
|
|
469
|
+
getContext: (bucketId) => readContext(bucketResourceId(requireValidBucketId(bucketId))),
|
|
470
|
+
getSession: (bucketId, sessionOptions) => getSessionForResource(bucketResourceId(requireValidBucketId(bucketId)), sessionOptions),
|
|
471
|
+
async getBucketAccess(bucketId) {
|
|
472
|
+
const safeBucketId = requireValidBucketId(bucketId);
|
|
473
|
+
const resourceId = bucketResourceId(safeBucketId);
|
|
474
|
+
const context = await readContext(resourceId);
|
|
475
|
+
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
476
|
+
const authInstance = await ensureStoredInstance();
|
|
477
|
+
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
478
|
+
const cacheKey = `${mfid}:${safeBucketId}:${authInstance.instanceId}`;
|
|
479
|
+
const cached = bucketAccessCache.get(cacheKey);
|
|
480
|
+
if (cached && cached.expiresAt > Date.now()) return cached.access;
|
|
481
|
+
const grant = normalizeBucketAccessGrant(context.bucketAccessGrant);
|
|
482
|
+
const remoteResourceId = context.remoteResourceId || resourceId;
|
|
483
|
+
if (!grant || grant.mfid !== mfid || grant.instanceId !== authInstance.instanceId || grant.resourceId !== remoteResourceId) {
|
|
484
|
+
throw new Error("bucket access grant unavailable; reauthorize required");
|
|
485
|
+
}
|
|
486
|
+
const keys = await unwrapBucketKeys(grant.envelope, authInstance.wrappingPrivateKey);
|
|
487
|
+
const access: BucketAccess = {
|
|
488
|
+
mfid,
|
|
489
|
+
instanceId: authInstance.instanceId,
|
|
490
|
+
bucketId: keys.bucketId,
|
|
491
|
+
resourceId: remoteResourceId,
|
|
492
|
+
...(context.resourceApiUrl ? { resourceApiUrl: context.resourceApiUrl } : {}),
|
|
493
|
+
capabilities: grant.capabilities,
|
|
494
|
+
grantRecordId: grant.grantRecordId,
|
|
495
|
+
keys,
|
|
496
|
+
};
|
|
497
|
+
bucketAccessCache.set(cacheKey, { access, expiresAt: Date.now() + BUCKET_ACCESS_CACHE_TTL_MS });
|
|
498
|
+
return access;
|
|
499
|
+
},
|
|
500
|
+
async clearContext(bucketId) {
|
|
501
|
+
const resourceId = bucketResourceId(requireValidBucketId(bucketId));
|
|
502
|
+
const authInstance = await readActiveStoredInstance();
|
|
503
|
+
if (authInstance) {
|
|
504
|
+
await storage.remove(contextKey(resourceId, authInstance.instanceId));
|
|
505
|
+
await storage.remove(sessionKey(resourceId, authInstance.instanceId));
|
|
506
|
+
}
|
|
507
|
+
if (currentResourceId === resourceId || !authInstance) {
|
|
508
|
+
mfid = "";
|
|
509
|
+
currentResourceId = "";
|
|
510
|
+
currentSession = null;
|
|
511
|
+
bucketAccessCache.clear();
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async function generateAuthInstance(): Promise<AuthInstance> {
|
|
518
|
+
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
519
|
+
const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
520
|
+
const signingPublicJwk = (await crypto.subtle.exportKey("jwk", signing.publicKey)) as JsonWebKey;
|
|
521
|
+
const wrappingPublicJwk = (await crypto.subtle.exportKey("jwk", wrapping.publicKey)) as JsonWebKey;
|
|
522
|
+
return {
|
|
523
|
+
v: 1,
|
|
524
|
+
instanceId: await deriveInstanceId(signingPublicJwk),
|
|
525
|
+
signingPublicJwk,
|
|
526
|
+
signingPrivateKey: signing.privateKey,
|
|
527
|
+
wrappingPublicJwk,
|
|
528
|
+
wrappingPrivateKey: wrapping.privateKey,
|
|
529
|
+
createdAt: new Date().toISOString(),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function deriveInstanceId(signingPublicJwk: JsonWebKey): Promise<string> {
|
|
534
|
+
const digest = await sha256Hex(stableStringify(jwkCore(signingPublicJwk)));
|
|
535
|
+
return `inst_${digest.slice(0, 32)}`;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export async function signInstanceChallenge(input: {
|
|
539
|
+
instance: Pick<AuthInstance, "instanceId" | "signingPrivateKey">;
|
|
540
|
+
challenge: string;
|
|
541
|
+
mfid: string;
|
|
542
|
+
resourceId: string;
|
|
543
|
+
challengeId?: string;
|
|
544
|
+
signedAt?: string;
|
|
545
|
+
}): Promise<InstanceProof> {
|
|
546
|
+
const signedAt = normalizeIsoDateTime(input.signedAt) || new Date().toISOString();
|
|
547
|
+
const payload = stableStringify({
|
|
548
|
+
v: 1,
|
|
549
|
+
type: "instance-proof",
|
|
550
|
+
instanceId: input.instance.instanceId,
|
|
551
|
+
challenge: input.challenge,
|
|
552
|
+
challengeId: input.challengeId || "",
|
|
553
|
+
mfid: input.mfid,
|
|
554
|
+
resourceId: input.resourceId,
|
|
555
|
+
signedAt,
|
|
556
|
+
});
|
|
557
|
+
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
|
|
558
|
+
return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
type AuthRequestFields = {
|
|
562
|
+
clientId: string;
|
|
563
|
+
requestId: string;
|
|
564
|
+
state: string;
|
|
565
|
+
redirectUri: string;
|
|
566
|
+
origin: string;
|
|
567
|
+
resourceId: string;
|
|
568
|
+
capabilities: AuthCapability[];
|
|
569
|
+
instanceId: string;
|
|
570
|
+
instanceSigningPublicJwk: JsonWebKey;
|
|
571
|
+
instanceWrappingPublicJwk: JsonWebKey;
|
|
572
|
+
createdAt: string;
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
function buildAuthRequestFragment(request: AuthRequestFields): string {
|
|
576
|
+
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
577
|
+
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
578
|
+
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
579
|
+
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
580
|
+
const redirect = new URL(request.redirectUri);
|
|
581
|
+
const origin = new URL(request.origin);
|
|
582
|
+
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
583
|
+
const wire = {
|
|
584
|
+
response_type: "code",
|
|
585
|
+
client_id: request.clientId,
|
|
586
|
+
redirect_uri: request.redirectUri,
|
|
587
|
+
state: request.state,
|
|
588
|
+
scope: request.capabilities.join(" "),
|
|
589
|
+
resource_id: request.resourceId,
|
|
590
|
+
mf_v: 1,
|
|
591
|
+
mf_auth_mode: "v1",
|
|
592
|
+
mf_request_id: request.requestId,
|
|
593
|
+
mf_instance_id: request.instanceId,
|
|
594
|
+
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
595
|
+
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
596
|
+
mf_issued_at: request.createdAt,
|
|
597
|
+
};
|
|
598
|
+
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl: string): EncryptedAuthAuthorizationResultEnvelope | null {
|
|
602
|
+
const input = String(fragmentOrUrl || "");
|
|
603
|
+
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
604
|
+
if (!rawFragment) return null;
|
|
605
|
+
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
606
|
+
if (!encoded) return null;
|
|
607
|
+
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded))) as Partial<EncryptedAuthAuthorizationResultEnvelope> | null;
|
|
608
|
+
if (
|
|
609
|
+
!envelope ||
|
|
610
|
+
envelope.v !== 1 ||
|
|
611
|
+
envelope.typ !== "auth.authorization-result.envelope.v1" ||
|
|
612
|
+
envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
|
|
613
|
+
typeof envelope.requestId !== "string" ||
|
|
614
|
+
typeof envelope.state !== "string" ||
|
|
615
|
+
!parseBucketResourceId(envelope.resourceId) ||
|
|
616
|
+
!isValidInstanceId(envelope.instanceId || "") ||
|
|
617
|
+
!isPublicP256EcJwk(envelope.ephemeralPublicJwk) ||
|
|
618
|
+
typeof envelope.salt !== "string" ||
|
|
619
|
+
typeof envelope.iv !== "string" ||
|
|
620
|
+
typeof envelope.aad !== "string" ||
|
|
621
|
+
typeof envelope.ciphertext !== "string"
|
|
622
|
+
) {
|
|
623
|
+
throw new Error("auth callback result fragment invalid");
|
|
624
|
+
}
|
|
625
|
+
return envelope as EncryptedAuthAuthorizationResultEnvelope;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export async function decryptEncryptedAuthAuthorizationResult(input: {
|
|
629
|
+
envelope: EncryptedAuthAuthorizationResultEnvelope;
|
|
630
|
+
instanceWrappingPrivateKey: CryptoKey;
|
|
631
|
+
expectedRequestId?: string;
|
|
632
|
+
expectedState?: string;
|
|
633
|
+
expectedResourceId?: string;
|
|
634
|
+
expectedInstanceId?: string;
|
|
635
|
+
}): Promise<StoredAuthAuthorizationResult> {
|
|
636
|
+
const { envelope } = input;
|
|
637
|
+
if (
|
|
638
|
+
(input.expectedRequestId && envelope.requestId !== input.expectedRequestId) ||
|
|
639
|
+
(input.expectedState && envelope.state !== input.expectedState) ||
|
|
640
|
+
(input.expectedResourceId && envelope.resourceId !== input.expectedResourceId) ||
|
|
641
|
+
(input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId)
|
|
642
|
+
) {
|
|
643
|
+
throw new Error("auth callback result mismatch");
|
|
644
|
+
}
|
|
645
|
+
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
646
|
+
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
|
|
647
|
+
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
648
|
+
const wrappingKey = await crypto.subtle.deriveKey(
|
|
649
|
+
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt) as BufferSource, info: utf8Encode(envelope.aad) },
|
|
650
|
+
material,
|
|
651
|
+
{ name: "AES-GCM", length: 256 },
|
|
652
|
+
false,
|
|
653
|
+
["decrypt"]
|
|
654
|
+
);
|
|
655
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
656
|
+
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv) as BufferSource, additionalData: utf8Encode(envelope.aad) },
|
|
657
|
+
wrappingKey,
|
|
658
|
+
b64urlToBytes(envelope.ciphertext) as BufferSource
|
|
659
|
+
);
|
|
660
|
+
const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
|
|
661
|
+
if (
|
|
662
|
+
!result ||
|
|
663
|
+
result.state !== envelope.state ||
|
|
664
|
+
result.resourceId !== envelope.resourceId ||
|
|
665
|
+
result.instanceId !== envelope.instanceId ||
|
|
666
|
+
(input.expectedState && result.state !== input.expectedState) ||
|
|
667
|
+
(input.expectedResourceId && result.resourceId !== input.expectedResourceId) ||
|
|
668
|
+
(input.expectedInstanceId && result.instanceId !== input.expectedInstanceId)
|
|
669
|
+
) {
|
|
670
|
+
throw new Error("auth callback result mismatch");
|
|
671
|
+
}
|
|
672
|
+
return result;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function normalizeAuthAuthorizationResult(value: unknown, expectedRequestId?: string): StoredAuthAuthorizationResult | null {
|
|
676
|
+
const row = value as Partial<StoredAuthAuthorizationResult> | null;
|
|
677
|
+
if (
|
|
678
|
+
!row ||
|
|
679
|
+
row.v !== 1 ||
|
|
680
|
+
row.result !== "approved" ||
|
|
681
|
+
typeof row.requestId !== "string" ||
|
|
682
|
+
(expectedRequestId && row.requestId !== expectedRequestId) ||
|
|
683
|
+
typeof row.state !== "string" ||
|
|
684
|
+
!isValidMfid(row.mfid || "") ||
|
|
685
|
+
!parseBucketResourceId(row.resourceId) ||
|
|
686
|
+
!isValidInstanceId(row.instanceId || "") ||
|
|
687
|
+
typeof row.createdAt !== "string"
|
|
688
|
+
) {
|
|
689
|
+
return null;
|
|
690
|
+
}
|
|
691
|
+
if (row.expiresAt !== undefined) {
|
|
692
|
+
const expiresAt = Date.parse(String(row.expiresAt));
|
|
693
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
694
|
+
}
|
|
695
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
696
|
+
if (!resource) return null;
|
|
697
|
+
const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
|
|
698
|
+
if (!bucketAccessGrant) return null;
|
|
699
|
+
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
return {
|
|
703
|
+
v: 1,
|
|
704
|
+
requestId: row.requestId,
|
|
705
|
+
state: row.state,
|
|
706
|
+
result: "approved",
|
|
707
|
+
mfid: row.mfid!,
|
|
708
|
+
resourceId: resource.resourceId,
|
|
709
|
+
instanceId: row.instanceId!,
|
|
710
|
+
createdAt: row.createdAt,
|
|
711
|
+
...(typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {}),
|
|
712
|
+
bucketAccessGrant,
|
|
713
|
+
...(row.expiresAt ? { expiresAt: row.expiresAt } : {}),
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
export function normalizeBucketAccessGrant(value: unknown): BucketAccessGrant | null {
|
|
718
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
719
|
+
const row = value as Partial<BucketAccessGrant>;
|
|
720
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
721
|
+
const capabilities = normalizeCapabilities(row.capabilities);
|
|
722
|
+
if (
|
|
723
|
+
row.v !== 1 ||
|
|
724
|
+
!/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) ||
|
|
725
|
+
!isValidMfid(row.mfid) ||
|
|
726
|
+
!resource ||
|
|
727
|
+
!isValidInstanceId(row.instanceId) ||
|
|
728
|
+
!/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
|
|
729
|
+
capabilities.length < 1 ||
|
|
730
|
+
!isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)
|
|
731
|
+
) {
|
|
732
|
+
return null;
|
|
733
|
+
}
|
|
734
|
+
return {
|
|
735
|
+
v: 1,
|
|
736
|
+
grantRecordId: row.grantRecordId!,
|
|
737
|
+
mfid: row.mfid!,
|
|
738
|
+
resourceId: resource.resourceId,
|
|
739
|
+
instanceId: row.instanceId!,
|
|
740
|
+
issuedAt: String(row.issuedAt || ""),
|
|
741
|
+
keyId: row.keyId!,
|
|
742
|
+
capabilities,
|
|
743
|
+
envelope: row.envelope as BucketKeyGrantEnvelope,
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function isValidBucketKeyGrantEnvelope(value: unknown, instanceId?: string, keyId?: string): value is BucketKeyGrantEnvelope {
|
|
748
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
749
|
+
const row = value as Partial<BucketKeyGrantEnvelope>;
|
|
750
|
+
if (
|
|
751
|
+
row.kind !== "bucket-key" ||
|
|
752
|
+
!isValidBucketId(row.bucketId) ||
|
|
753
|
+
!/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
|
|
754
|
+
!isValidInstanceId(row.targetInstanceId) ||
|
|
755
|
+
row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
|
|
756
|
+
!isPublicP256EcJwk(row.targetWrappingPublicJwk) ||
|
|
757
|
+
!isPublicP256EcJwk(row.ephemeralPublicJwk) ||
|
|
758
|
+
typeof row.salt !== "string" ||
|
|
759
|
+
typeof row.iv !== "string" ||
|
|
760
|
+
typeof row.aad !== "string" ||
|
|
761
|
+
typeof row.ciphertext !== "string"
|
|
762
|
+
) {
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
766
|
+
if (keyId && row.keyId !== keyId) return false;
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
export function bucketResourceId(bucketId: string): string {
|
|
771
|
+
return `urn:myfield:bucket:${bucketId}`;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function parseBucketResourceId(resourceId: unknown): { resourceId: string; bucketId: string } | null {
|
|
775
|
+
const safe = typeof resourceId === "string" ? resourceId.trim() : "";
|
|
776
|
+
const prefix = "urn:myfield:bucket:";
|
|
777
|
+
if (!safe.startsWith(prefix)) return null;
|
|
778
|
+
const bucketId = safe.slice(prefix.length);
|
|
779
|
+
return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function normalizeCapabilities(input: unknown): AuthCapability[] {
|
|
783
|
+
if (!Array.isArray(input)) return [];
|
|
784
|
+
const allowed = new Set<AuthCapability>(["read", "write"]);
|
|
785
|
+
const result: AuthCapability[] = [];
|
|
786
|
+
for (const item of input) {
|
|
787
|
+
if (allowed.has(item as AuthCapability) && !result.includes(item as AuthCapability)) result.push(item as AuthCapability);
|
|
788
|
+
}
|
|
789
|
+
return result.sort();
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
async function postJson<T>(fetchImpl: typeof fetch, apiBase: string | undefined, path: string, body: unknown): Promise<T> {
|
|
793
|
+
const res = await fetchImpl(`${apiBase || ""}${path}`, {
|
|
794
|
+
method: "POST",
|
|
795
|
+
headers: { "content-type": "application/json" },
|
|
796
|
+
body: JSON.stringify(body),
|
|
797
|
+
});
|
|
798
|
+
if (!res.ok) {
|
|
799
|
+
const text = await res.text().catch(() => "");
|
|
800
|
+
throw new Error(`${path} failed: ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
|
801
|
+
}
|
|
802
|
+
return (await res.json()) as T;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
function getSessionRemainingMs(session: CloudSessionCredential | null): number | null {
|
|
806
|
+
if (!session || session.carrier !== "bearer") return null;
|
|
807
|
+
const expiresAt = Date.parse(session.expiresAt);
|
|
808
|
+
return Number.isFinite(expiresAt) ? expiresAt - Date.now() : null;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
function isSessionUsable(session: CloudSessionCredential | null): session is CloudSessionCredential {
|
|
812
|
+
const remainingMs = getSessionRemainingMs(session);
|
|
813
|
+
return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
function shouldBestEffortRefreshSession(session: CloudSessionCredential): boolean {
|
|
817
|
+
const remainingMs = getSessionRemainingMs(session);
|
|
818
|
+
return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS && remainingMs <= INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function isFresh(createdAt: string): boolean {
|
|
822
|
+
const created = Date.parse(createdAt);
|
|
823
|
+
return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
export function isValidBucketId(value: unknown): value is string {
|
|
827
|
+
const safe = typeof value === "string" ? value.trim() : "";
|
|
828
|
+
return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function requireValidBucketId(value: unknown): string {
|
|
832
|
+
if (!isValidBucketId(value)) throw new Error("invalid bucketId");
|
|
833
|
+
return value;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
function isValidInstanceId(value: unknown): value is string {
|
|
837
|
+
return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function isValidMfid(value: unknown): value is string {
|
|
841
|
+
return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function isPublicP256EcJwk(value: unknown): value is JsonWebKey {
|
|
845
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
846
|
+
const jwk = value as JsonWebKey;
|
|
847
|
+
return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function normalizeInstanceAppId(value: unknown): string {
|
|
851
|
+
const safe = typeof value === "string" ? value.trim() : "";
|
|
852
|
+
return isValidBucketId(safe) ? safe : "myfield.sdk";
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function seg(value: string): string {
|
|
856
|
+
return encodeURIComponent(value);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function jwkCore(jwk: JsonWebKey): Record<string, string> {
|
|
860
|
+
const out: Record<string, string> = {};
|
|
861
|
+
for (const key of ["kty", "crv", "x", "y", "kid", "alg", "use"] as const) {
|
|
862
|
+
const value = (jwk as Record<string, unknown>)[key];
|
|
863
|
+
if (typeof value === "string") out[key] = value;
|
|
864
|
+
}
|
|
865
|
+
return out;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
function browserLocationHref(): string {
|
|
869
|
+
if (typeof window === "undefined") throw new Error("browser window required");
|
|
870
|
+
return window.location.href;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function browserLocationOrigin(): string {
|
|
874
|
+
if (typeof window === "undefined") throw new Error("browser window required");
|
|
875
|
+
return window.location.origin;
|
|
876
|
+
}
|