@myfield/sdk 0.9.2 → 0.9.3
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 +7 -0
- package/README.md +30 -9
- package/dist/index.js +467 -366
- package/package.json +15 -8
- package/types/index.d.ts +395 -137
- package/docs/API.md +0 -298
- package/docs/BUCKET-SPEC.md +0 -173
- package/src/auth/authorization.ts +0 -254
- package/src/auth/flow.ts +0 -93
- package/src/auth/identifiers.ts +0 -46
- package/src/auth/index.ts +0 -17
- package/src/auth/instance.ts +0 -395
- package/src/auth/keys.ts +0 -73
- package/src/auth/proof.ts +0 -26
- package/src/auth/session.ts +0 -16
- package/src/auth/store.ts +0 -90
- package/src/auth/types.ts +0 -47
- package/src/bucket/binary.ts +0 -253
- package/src/bucket/client.ts +0 -426
- package/src/bucket/crypto.ts +0 -58
- package/src/bucket/format.ts +0 -324
- package/src/bucket/index.ts +0 -40
- package/src/bucket/keys.ts +0 -104
- package/src/bucket/store.ts +0 -190
- package/src/bucket/transport.ts +0 -249
- package/src/errors.ts +0 -40
- package/src/facade.ts +0 -698
- package/src/index.ts +0 -29
- package/src/internal/encoding.ts +0 -95
- package/src/remote/bucket.ts +0 -180
- package/src/remote/client.ts +0 -38
- package/src/remote/connection.ts +0 -529
- package/src/remote/feed.ts +0 -80
- package/src/remote/http.ts +0 -78
- package/src/remote/session.ts +0 -31
package/src/auth/instance.ts
DELETED
|
@@ -1,395 +0,0 @@
|
|
|
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 { bytesToHex, randomId } from "../internal/encoding.ts";
|
|
13
|
-
import { unwrapBucketKeys } from "../bucket/keys.ts";
|
|
14
|
-
import { createIndexedDbStorageAdapter, type StorageAdapter } from "../bucket/store.ts";
|
|
15
|
-
import type { AuthInstance } from "./keys.ts";
|
|
16
|
-
import { createInstanceKeyStore } from "./store.ts";
|
|
17
|
-
import { ClientError } from "../errors.ts";
|
|
18
|
-
import type { AuthCapability, InstanceAuthContext, BucketAccess, AuthCallbackResult, BucketAccessGrant } from "./types.ts";
|
|
19
|
-
import { buildAuthRequestFragment, parseEncryptedAuthAuthorizationResultFragment, decryptEncryptedAuthAuthorizationResult,
|
|
20
|
-
normalizeBucketAccessGrant, type StoredAuthAuthorizationResult, type EncryptedAuthAuthorizationResultEnvelope } from "./authorization.ts";
|
|
21
|
-
import { bucketResourceId, parseBucketResourceId, requireValidBucketId, isValidMfid, resolveAppId } from "./identifiers.ts";
|
|
22
|
-
import { createSessionClient } from "../remote/session.ts";
|
|
23
|
-
import { createSession, type CloudSessionCredential } from "./session.ts";
|
|
24
|
-
|
|
25
|
-
export type { AuthCapability, InstanceAuthContext, BucketAccess, AuthCallbackResult, BucketAccessGrant } from "./types.ts";
|
|
26
|
-
export { decryptEncryptedAuthAuthorizationResult, normalizeBucketAccessGrant } from "./authorization.ts";
|
|
27
|
-
export { bucketResourceId, isValidBucketId } from "./identifiers.ts";
|
|
28
|
-
export type { AuthInstance } from "./keys.ts";
|
|
29
|
-
export type { CloudSessionCredential } from "./session.ts";
|
|
30
|
-
export { signInstanceChallenge } from "./proof.ts";
|
|
31
|
-
|
|
32
|
-
export type InstanceAuthClientOptions = {
|
|
33
|
-
appId?: string;
|
|
34
|
-
apiBase?: string;
|
|
35
|
-
authPageUrl?: string;
|
|
36
|
-
redirectUri?: string;
|
|
37
|
-
origin?: string;
|
|
38
|
-
openAuthUrl?: (url: string) => void | Promise<void>;
|
|
39
|
-
storage?: StorageAdapter;
|
|
40
|
-
fetchImpl?: typeof fetch;
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export type InstanceAuthClient = {
|
|
44
|
-
ensureInstance(): Promise<AuthInstance>;
|
|
45
|
-
authorize(request: { bucketId: string }): Promise<void>;
|
|
46
|
-
handleCallback(url?: string): Promise<AuthCallbackResult | null>;
|
|
47
|
-
getContext(bucketId: string): Promise<InstanceAuthContext | null>;
|
|
48
|
-
getSession(bucketId: string, options?: { forceRefresh?: boolean }): Promise<CloudSessionCredential>;
|
|
49
|
-
getBucketAccess(bucketId: string): Promise<BucketAccess>;
|
|
50
|
-
clearContext(bucketId: string): Promise<void>;
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
type PendingInstanceAuthRequest = {
|
|
54
|
-
v: 1;
|
|
55
|
-
requestId: string;
|
|
56
|
-
state: string;
|
|
57
|
-
resourceId: string;
|
|
58
|
-
capabilities: AuthCapability[];
|
|
59
|
-
instanceId: string;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
type InstanceAuthCallbackPointer = {
|
|
63
|
-
v: 1;
|
|
64
|
-
requestId: string;
|
|
65
|
-
resourceId: string;
|
|
66
|
-
instanceId: string;
|
|
67
|
-
pendingKey: string;
|
|
68
|
-
createdAt: string;
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
type StoredCloudSessionCredential = {
|
|
72
|
-
v: 1;
|
|
73
|
-
mfid: string;
|
|
74
|
-
resourceId: string;
|
|
75
|
-
instanceId: string;
|
|
76
|
-
credential: CloudSessionCredential;
|
|
77
|
-
storedAt?: string;
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
const AUTH_REQUEST_TTL_MS = 10 * 60 * 1000;
|
|
81
|
-
const DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
|
|
82
|
-
const BUCKET_ACCESS_CACHE_TTL_MS = 60_000;
|
|
83
|
-
const INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1000;
|
|
84
|
-
const INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1000;
|
|
85
|
-
const FIXED_CAPABILITIES: AuthCapability[] = ["read", "write"];
|
|
86
|
-
|
|
87
|
-
export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}): InstanceAuthClient {
|
|
88
|
-
const appId = resolveAppId(options.appId);
|
|
89
|
-
let mfid = "";
|
|
90
|
-
let currentResourceId = "";
|
|
91
|
-
let currentSession: { resourceId: string; credential: CloudSessionCredential } | null = null;
|
|
92
|
-
const inFlightSessionRefreshes = new Map<string, Promise<CloudSessionCredential>>();
|
|
93
|
-
const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
|
|
94
|
-
const fetchImpl = options.fetchImpl || fetch;
|
|
95
|
-
const sessions = createSessionClient((path, body) => postJson(fetchImpl, options.apiBase, path, body));
|
|
96
|
-
const bucketAccessCache = new Map<string, { access: BucketAccess; expiresAt: number }>();
|
|
97
|
-
|
|
98
|
-
const keyStore = createInstanceKeyStore(storage, appId);
|
|
99
|
-
const { pending: pendingAuthKey, callback: callbackPointerKey, context: contextKey, session: sessionKey } = keyStore.keys;
|
|
100
|
-
const readStoredInstance = keyStore.read;
|
|
101
|
-
const readActiveStoredInstance = keyStore.active;
|
|
102
|
-
const ensureStoredInstance = keyStore.ensure;
|
|
103
|
-
|
|
104
|
-
async function readContext(resourceId: string): Promise<InstanceAuthContext | null> {
|
|
105
|
-
if (!parseBucketResourceId(resourceId)) return null;
|
|
106
|
-
const authInstance = await readActiveStoredInstance();
|
|
107
|
-
if (!authInstance) return null;
|
|
108
|
-
const context = await storage.get<InstanceAuthContext>(contextKey(resourceId, authInstance.instanceId));
|
|
109
|
-
if (
|
|
110
|
-
!context ||
|
|
111
|
-
context.v !== 1 ||
|
|
112
|
-
!isValidMfid(context.mfid) ||
|
|
113
|
-
context.resourceId !== resourceId ||
|
|
114
|
-
(context.remoteResourceId !== undefined && !parseBucketResourceId(context.remoteResourceId)) ||
|
|
115
|
-
context.instanceId !== authInstance.instanceId
|
|
116
|
-
) {
|
|
117
|
-
return null;
|
|
118
|
-
}
|
|
119
|
-
mfid = context.mfid;
|
|
120
|
-
currentResourceId = context.resourceId;
|
|
121
|
-
return context;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
async function getSessionForResource(resourceId: string, sessionOptions?: { forceRefresh?: boolean }): Promise<CloudSessionCredential> {
|
|
125
|
-
const context = await readContext(resourceId);
|
|
126
|
-
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
127
|
-
const authInstance = await ensureStoredInstance();
|
|
128
|
-
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
129
|
-
const sessionResourceId = context.remoteResourceId || context.resourceId;
|
|
130
|
-
const forceRefresh = sessionOptions?.forceRefresh === true;
|
|
131
|
-
const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
|
|
132
|
-
|
|
133
|
-
const performRefreshSession = async (): Promise<CloudSessionCredential> => {
|
|
134
|
-
const credential = await createSession({ instance: authInstance, mfid, resourceId: sessionResourceId }, sessions);
|
|
135
|
-
currentSession = { resourceId: sessionResourceId, credential };
|
|
136
|
-
if (credential.carrier === "bearer") {
|
|
137
|
-
await storage.set(sessionKey(sessionResourceId, context.instanceId), {
|
|
138
|
-
v: 1,
|
|
139
|
-
mfid,
|
|
140
|
-
resourceId: sessionResourceId,
|
|
141
|
-
instanceId: authInstance.instanceId,
|
|
142
|
-
credential,
|
|
143
|
-
storedAt: new Date().toISOString(),
|
|
144
|
-
} satisfies StoredCloudSessionCredential);
|
|
145
|
-
}
|
|
146
|
-
return credential;
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
const refreshSession = (): Promise<CloudSessionCredential> => {
|
|
150
|
-
const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
|
|
151
|
-
if (inFlight) return inFlight;
|
|
152
|
-
const promise = performRefreshSession().finally(() => {
|
|
153
|
-
if (inFlightSessionRefreshes.get(refreshSessionKey) === promise) inFlightSessionRefreshes.delete(refreshSessionKey);
|
|
154
|
-
});
|
|
155
|
-
inFlightSessionRefreshes.set(refreshSessionKey, promise);
|
|
156
|
-
return promise;
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
if (!forceRefresh) {
|
|
160
|
-
let cachedCredential: CloudSessionCredential | null = null;
|
|
161
|
-
if (currentSession?.resourceId === sessionResourceId && isSessionUsable(currentSession.credential)) {
|
|
162
|
-
cachedCredential = currentSession.credential;
|
|
163
|
-
} else {
|
|
164
|
-
const stored = await storage.get<StoredCloudSessionCredential>(sessionKey(sessionResourceId, context.instanceId));
|
|
165
|
-
if (
|
|
166
|
-
stored?.v === 1 &&
|
|
167
|
-
stored.mfid === mfid &&
|
|
168
|
-
stored.resourceId === sessionResourceId &&
|
|
169
|
-
stored.instanceId === authInstance.instanceId &&
|
|
170
|
-
isSessionUsable(stored.credential)
|
|
171
|
-
) {
|
|
172
|
-
currentSession = { resourceId: sessionResourceId, credential: stored.credential };
|
|
173
|
-
cachedCredential = stored.credential;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
if (cachedCredential) {
|
|
177
|
-
if (shouldBestEffortRefreshSession(cachedCredential)) void refreshSession().catch(() => undefined);
|
|
178
|
-
return cachedCredential;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
if (forceRefresh) inFlightSessionRefreshes.delete(refreshSessionKey);
|
|
183
|
-
return refreshSession();
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
async ensureInstance() {
|
|
188
|
-
return ensureStoredInstance();
|
|
189
|
-
},
|
|
190
|
-
async authorize(request) {
|
|
191
|
-
const resourceId = bucketResourceId(requireValidBucketId(request.bucketId));
|
|
192
|
-
const authInstance = await ensureStoredInstance();
|
|
193
|
-
currentResourceId = resourceId;
|
|
194
|
-
const state = randomId("state");
|
|
195
|
-
const requestId = randomId("req");
|
|
196
|
-
const nextPendingKey = pendingAuthKey(resourceId, authInstance.instanceId);
|
|
197
|
-
const fragment = buildAuthRequestFragment({
|
|
198
|
-
clientId: appId,
|
|
199
|
-
requestId,
|
|
200
|
-
state,
|
|
201
|
-
redirectUri: options.redirectUri || browserLocationHref(),
|
|
202
|
-
origin: options.origin || browserLocationOrigin(),
|
|
203
|
-
resourceId,
|
|
204
|
-
capabilities: FIXED_CAPABILITIES,
|
|
205
|
-
instanceId: authInstance.instanceId,
|
|
206
|
-
instanceSigningPublicJwk: authInstance.signingPublicJwk,
|
|
207
|
-
instanceWrappingPublicJwk: authInstance.wrappingPublicJwk,
|
|
208
|
-
createdAt: new Date().toISOString(),
|
|
209
|
-
});
|
|
210
|
-
await storage.set(nextPendingKey, {
|
|
211
|
-
v: 1,
|
|
212
|
-
requestId,
|
|
213
|
-
state,
|
|
214
|
-
resourceId,
|
|
215
|
-
capabilities: FIXED_CAPABILITIES,
|
|
216
|
-
instanceId: authInstance.instanceId,
|
|
217
|
-
} satisfies PendingInstanceAuthRequest);
|
|
218
|
-
await storage.set(callbackPointerKey(requestId), {
|
|
219
|
-
v: 1,
|
|
220
|
-
requestId,
|
|
221
|
-
resourceId,
|
|
222
|
-
instanceId: authInstance.instanceId,
|
|
223
|
-
pendingKey: nextPendingKey,
|
|
224
|
-
createdAt: new Date().toISOString(),
|
|
225
|
-
} satisfies InstanceAuthCallbackPointer);
|
|
226
|
-
const authPageUrl = String(options.authPageUrl || "").trim();
|
|
227
|
-
if (!authPageUrl) throw new Error("authPageUrl is required to authorize an instance");
|
|
228
|
-
const authUrl = `${authPageUrl}${fragment}`;
|
|
229
|
-
if (options.openAuthUrl) {
|
|
230
|
-
await options.openAuthUrl(authUrl);
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
if (typeof window === "undefined") throw new Error("browser window required for authorize redirect");
|
|
234
|
-
window.location.href = authUrl;
|
|
235
|
-
},
|
|
236
|
-
async handleCallback(url) {
|
|
237
|
-
const parsed = url && /^[a-z][a-z0-9+.-]*:/i.test(url) ? new URL(url) : new URL(url || browserLocationHref(), browserLocationOrigin());
|
|
238
|
-
let encryptedEnvelope: EncryptedAuthAuthorizationResultEnvelope | null = null;
|
|
239
|
-
let encryptedEnvelopeInvalid = false;
|
|
240
|
-
try {
|
|
241
|
-
encryptedEnvelope = parseEncryptedAuthAuthorizationResultFragment(parsed.hash);
|
|
242
|
-
} catch {
|
|
243
|
-
encryptedEnvelopeInvalid = true;
|
|
244
|
-
}
|
|
245
|
-
const result: AuthCallbackResult = {
|
|
246
|
-
requestId: parsed.searchParams.get("mf_request_id") || "",
|
|
247
|
-
state: parsed.searchParams.get("state") || "",
|
|
248
|
-
result: (parsed.searchParams.get("mf_result") || (parsed.searchParams.get("error") ? "error" : "")) as AuthCallbackResult["result"],
|
|
249
|
-
...(parsed.searchParams.get("error") ? { error: parsed.searchParams.get("error") || undefined } : {}),
|
|
250
|
-
...(parsed.searchParams.get("error_description") ? { errorDescription: parsed.searchParams.get("error_description") || undefined } : {}),
|
|
251
|
-
};
|
|
252
|
-
if (!result.requestId || !result.state || !["approved", "denied", "error"].includes(result.result)) return null;
|
|
253
|
-
const pointer = await storage.get<InstanceAuthCallbackPointer>(callbackPointerKey(result.requestId));
|
|
254
|
-
if (!pointer || pointer.v !== 1 || pointer.requestId !== result.requestId || !isFresh(pointer.createdAt)) return null;
|
|
255
|
-
const expected = await storage.get<PendingInstanceAuthRequest>(pointer.pendingKey);
|
|
256
|
-
if (!expected || expected.v !== 1 || expected.requestId !== result.requestId || expected.state !== result.state) return null;
|
|
257
|
-
result.resourceId = expected.resourceId;
|
|
258
|
-
if (result.result === "approved") {
|
|
259
|
-
if (encryptedEnvelopeInvalid || !encryptedEnvelope) {
|
|
260
|
-
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_result_invalid" };
|
|
261
|
-
}
|
|
262
|
-
const authInstance = await readStoredInstance(expected.instanceId);
|
|
263
|
-
if (!authInstance) return { ...result, result: "error", error: "server_error", errorDescription: "authorization_instance_missing" };
|
|
264
|
-
let stored: StoredAuthAuthorizationResult;
|
|
265
|
-
try {
|
|
266
|
-
stored = await decryptEncryptedAuthAuthorizationResult({
|
|
267
|
-
envelope: encryptedEnvelope,
|
|
268
|
-
instanceWrappingPrivateKey: authInstance.wrappingPrivateKey,
|
|
269
|
-
expectedRequestId: result.requestId,
|
|
270
|
-
expectedState: result.state,
|
|
271
|
-
expectedResourceId: expected.resourceId,
|
|
272
|
-
expectedInstanceId: expected.instanceId,
|
|
273
|
-
});
|
|
274
|
-
} catch {
|
|
275
|
-
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_result_invalid" };
|
|
276
|
-
}
|
|
277
|
-
if (stored.resourceId !== pointer.resourceId || stored.instanceId !== pointer.instanceId) {
|
|
278
|
-
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_context_mismatch" };
|
|
279
|
-
}
|
|
280
|
-
const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
|
|
281
|
-
mfid = stored.mfid;
|
|
282
|
-
currentResourceId = stored.resourceId;
|
|
283
|
-
if ((await readActiveStoredInstance())?.instanceId !== authInstance.instanceId) {
|
|
284
|
-
throw new ClientError("IDENTITY_MISMATCH", "Active instance changed during authorization");
|
|
285
|
-
}
|
|
286
|
-
await storage.set(contextKey(stored.resourceId, stored.instanceId), {
|
|
287
|
-
v: 1,
|
|
288
|
-
mfid: stored.mfid,
|
|
289
|
-
resourceId: stored.resourceId,
|
|
290
|
-
...(remoteResourceId !== stored.resourceId ? { remoteResourceId } : {}),
|
|
291
|
-
...(stored.resourceApiUrl ? { resourceApiUrl: stored.resourceApiUrl } : {}),
|
|
292
|
-
instanceId: stored.instanceId,
|
|
293
|
-
requestId: result.requestId,
|
|
294
|
-
authorizedAt: new Date().toISOString(),
|
|
295
|
-
...(stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}),
|
|
296
|
-
} satisfies InstanceAuthContext);
|
|
297
|
-
if (currentSession?.resourceId === remoteResourceId) currentSession = null;
|
|
298
|
-
await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
|
|
299
|
-
bucketAccessCache.clear();
|
|
300
|
-
}
|
|
301
|
-
await storage.remove(pointer.pendingKey);
|
|
302
|
-
await storage.remove(callbackPointerKey(result.requestId));
|
|
303
|
-
return result;
|
|
304
|
-
},
|
|
305
|
-
getContext: (bucketId) => readContext(bucketResourceId(requireValidBucketId(bucketId))),
|
|
306
|
-
getSession: (bucketId, sessionOptions) => getSessionForResource(bucketResourceId(requireValidBucketId(bucketId)), sessionOptions),
|
|
307
|
-
async getBucketAccess(bucketId) {
|
|
308
|
-
const safeBucketId = requireValidBucketId(bucketId);
|
|
309
|
-
const resourceId = bucketResourceId(safeBucketId);
|
|
310
|
-
const context = await readContext(resourceId);
|
|
311
|
-
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
312
|
-
const authInstance = await ensureStoredInstance();
|
|
313
|
-
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
314
|
-
const cacheKey = `${mfid}:${safeBucketId}:${authInstance.instanceId}`;
|
|
315
|
-
const cached = bucketAccessCache.get(cacheKey);
|
|
316
|
-
if (cached && cached.expiresAt > Date.now()) return cached.access;
|
|
317
|
-
const grant = normalizeBucketAccessGrant(context.bucketAccessGrant);
|
|
318
|
-
const remoteResourceId = context.remoteResourceId || resourceId;
|
|
319
|
-
if (!grant || grant.mfid !== mfid || grant.instanceId !== authInstance.instanceId || grant.resourceId !== remoteResourceId) {
|
|
320
|
-
throw new Error("bucket access grant unavailable; reauthorize required");
|
|
321
|
-
}
|
|
322
|
-
const keys = await unwrapBucketKeys(grant.envelope, authInstance.wrappingPrivateKey);
|
|
323
|
-
const access: BucketAccess = {
|
|
324
|
-
mfid,
|
|
325
|
-
instanceId: authInstance.instanceId,
|
|
326
|
-
bucketId: keys.bucketId,
|
|
327
|
-
resourceId: remoteResourceId,
|
|
328
|
-
...(context.resourceApiUrl ? { resourceApiUrl: context.resourceApiUrl } : {}),
|
|
329
|
-
capabilities: grant.capabilities,
|
|
330
|
-
grantRecordId: grant.grantRecordId,
|
|
331
|
-
keys,
|
|
332
|
-
};
|
|
333
|
-
bucketAccessCache.set(cacheKey, { access, expiresAt: Date.now() + BUCKET_ACCESS_CACHE_TTL_MS });
|
|
334
|
-
return access;
|
|
335
|
-
},
|
|
336
|
-
async clearContext(bucketId) {
|
|
337
|
-
const resourceId = bucketResourceId(requireValidBucketId(bucketId));
|
|
338
|
-
const authInstance = await readActiveStoredInstance();
|
|
339
|
-
if (authInstance) {
|
|
340
|
-
await storage.remove(contextKey(resourceId, authInstance.instanceId));
|
|
341
|
-
await storage.remove(sessionKey(resourceId, authInstance.instanceId));
|
|
342
|
-
}
|
|
343
|
-
if (currentResourceId === resourceId || !authInstance) {
|
|
344
|
-
mfid = "";
|
|
345
|
-
currentResourceId = "";
|
|
346
|
-
currentSession = null;
|
|
347
|
-
bucketAccessCache.clear();
|
|
348
|
-
}
|
|
349
|
-
},
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
async function postJson<T>(fetchImpl: typeof fetch, apiBase: string | undefined, path: string, body: unknown): Promise<T> {
|
|
354
|
-
const res = await fetchImpl(`${apiBase || ""}${path}`, {
|
|
355
|
-
method: "POST",
|
|
356
|
-
headers: { "content-type": "application/json" },
|
|
357
|
-
body: JSON.stringify(body),
|
|
358
|
-
});
|
|
359
|
-
if (!res.ok) {
|
|
360
|
-
const text = await res.text().catch(() => "");
|
|
361
|
-
throw new Error(`${path} failed: ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
|
362
|
-
}
|
|
363
|
-
return (await res.json()) as T;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
function getSessionRemainingMs(session: CloudSessionCredential | null): number | null {
|
|
367
|
-
if (!session || session.carrier !== "bearer") return null;
|
|
368
|
-
const expiresAt = Date.parse(session.expiresAt);
|
|
369
|
-
return Number.isFinite(expiresAt) ? expiresAt - Date.now() : null;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
function isSessionUsable(session: CloudSessionCredential | null): session is CloudSessionCredential {
|
|
373
|
-
const remainingMs = getSessionRemainingMs(session);
|
|
374
|
-
return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
function shouldBestEffortRefreshSession(session: CloudSessionCredential): boolean {
|
|
378
|
-
const remainingMs = getSessionRemainingMs(session);
|
|
379
|
-
return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS && remainingMs <= INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
function isFresh(createdAt: string): boolean {
|
|
383
|
-
const created = Date.parse(createdAt);
|
|
384
|
-
return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
function browserLocationHref(): string {
|
|
388
|
-
if (typeof window === "undefined") throw new Error("browser window required");
|
|
389
|
-
return window.location.href;
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
function browserLocationOrigin(): string {
|
|
393
|
-
if (typeof window === "undefined") throw new Error("browser window required");
|
|
394
|
-
return window.location.origin;
|
|
395
|
-
}
|
package/src/auth/keys.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import { ClientError } from "../errors.ts";
|
|
2
|
-
import { sha256Hex, stableStringify } from "../internal/encoding.ts";
|
|
3
|
-
|
|
4
|
-
export type AuthInstance = {
|
|
5
|
-
v: 1;
|
|
6
|
-
instanceId: string;
|
|
7
|
-
signingPublicJwk: JsonWebKey;
|
|
8
|
-
signingPrivateKey: CryptoKey;
|
|
9
|
-
wrappingPublicJwk: JsonWebKey;
|
|
10
|
-
wrappingPrivateKey: CryptoKey;
|
|
11
|
-
createdAt: string;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
export async function createInstanceKey(): Promise<AuthInstance> {
|
|
15
|
-
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
16
|
-
const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
17
|
-
const signingPublicJwk = (await crypto.subtle.exportKey("jwk", signing.publicKey)) as JsonWebKey;
|
|
18
|
-
const wrappingPublicJwk = (await crypto.subtle.exportKey("jwk", wrapping.publicKey)) as JsonWebKey;
|
|
19
|
-
return {
|
|
20
|
-
v: 1,
|
|
21
|
-
instanceId: await deriveInstanceId(signingPublicJwk),
|
|
22
|
-
signingPublicJwk,
|
|
23
|
-
signingPrivateKey: signing.privateKey,
|
|
24
|
-
wrappingPublicJwk,
|
|
25
|
-
wrappingPrivateKey: wrapping.privateKey,
|
|
26
|
-
createdAt: new Date().toISOString(),
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function deriveInstanceId(signingPublicJwk: JsonWebKey): Promise<string> {
|
|
31
|
-
const core = {
|
|
32
|
-
kty: String(signingPublicJwk.kty || ""),
|
|
33
|
-
crv: String(signingPublicJwk.crv || ""),
|
|
34
|
-
x: String(signingPublicJwk.x || ""),
|
|
35
|
-
y: String(signingPublicJwk.y || ""),
|
|
36
|
-
};
|
|
37
|
-
const digest = await sha256Hex(stableStringify(core));
|
|
38
|
-
return `inst_${digest.slice(0, 32)}`;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export type InstanceKey = Omit<AuthInstance, "v">;
|
|
42
|
-
|
|
43
|
-
export function toInstanceKey(value: AuthInstance): InstanceKey {
|
|
44
|
-
return { instanceId: value.instanceId, signingPublicJwk: { ...value.signingPublicJwk },
|
|
45
|
-
signingPrivateKey: value.signingPrivateKey, wrappingPublicJwk: { ...value.wrappingPublicJwk },
|
|
46
|
-
wrappingPrivateKey: value.wrappingPrivateKey, createdAt: value.createdAt };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export async function validateInstanceKey(value: InstanceKey): Promise<AuthInstance> {
|
|
50
|
-
const invalid = (cause?: unknown) => new ClientError("INVALID_INPUT", "Invalid instance key", { cause });
|
|
51
|
-
try {
|
|
52
|
-
if (!value || typeof value !== "object" || typeof value.createdAt !== "string"
|
|
53
|
-
|| !value.createdAt.endsWith("Z") || !Number.isFinite(Date.parse(value.createdAt))) throw invalid();
|
|
54
|
-
value = { ...value, signingPublicJwk: { ...value.signingPublicJwk }, wrappingPublicJwk: { ...value.wrappingPublicJwk } };
|
|
55
|
-
const { signingPrivateKey: sign, wrappingPrivateKey: wrap } = value;
|
|
56
|
-
for (const [key, name, usage] of [[sign, "ECDSA", "sign"], [wrap, "ECDH", "deriveBits"]] as const) {
|
|
57
|
-
if (!(key instanceof CryptoKey) || key.type !== "private" || key.extractable || key.algorithm.name !== name
|
|
58
|
-
|| (key.algorithm as EcKeyAlgorithm).namedCurve !== "P-256" || !key.usages.includes(usage)) throw invalid();
|
|
59
|
-
}
|
|
60
|
-
if (value.instanceId !== await deriveInstanceId(value.signingPublicJwk)) throw invalid();
|
|
61
|
-
const publicSign = await crypto.subtle.importKey("jwk", value.signingPublicJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
|
|
62
|
-
const challenge = crypto.getRandomValues(new Uint8Array(32));
|
|
63
|
-
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, sign, challenge);
|
|
64
|
-
if (!await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicSign, signature, challenge)) throw invalid();
|
|
65
|
-
const publicWrap = await crypto.subtle.importKey("jwk", value.wrappingPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
66
|
-
const ephemeral = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
67
|
-
const left = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeral.publicKey }, wrap, 256));
|
|
68
|
-
const right = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: publicWrap }, ephemeral.privateKey, 256));
|
|
69
|
-
if (!left.every((byte, i) => byte === right[i])) throw invalid();
|
|
70
|
-
return { v: 1, instanceId: value.instanceId, signingPublicJwk: { ...value.signingPublicJwk }, signingPrivateKey: sign,
|
|
71
|
-
wrappingPublicJwk: { ...value.wrappingPublicJwk }, wrappingPrivateKey: wrap, createdAt: value.createdAt };
|
|
72
|
-
} catch (cause) { throw cause instanceof ClientError ? cause : invalid(cause); }
|
|
73
|
-
}
|
package/src/auth/proof.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { bytesToB64url, normalizeIsoDateTime, stableStringify, utf8Encode } from "../internal/encoding.ts";
|
|
2
|
-
import type { AuthInstance } from "./keys.ts";
|
|
3
|
-
import type { InstanceProof } from "../remote/session.ts";
|
|
4
|
-
|
|
5
|
-
export async function signInstanceChallenge(input: {
|
|
6
|
-
instance: Pick<AuthInstance, "instanceId" | "signingPrivateKey">;
|
|
7
|
-
challenge: string;
|
|
8
|
-
mfid: string;
|
|
9
|
-
resourceId: string;
|
|
10
|
-
challengeId?: string;
|
|
11
|
-
signedAt?: string;
|
|
12
|
-
}): Promise<InstanceProof> {
|
|
13
|
-
const signedAt = normalizeIsoDateTime(input.signedAt) || new Date().toISOString();
|
|
14
|
-
const payload = stableStringify({
|
|
15
|
-
v: 1,
|
|
16
|
-
type: "instance-proof",
|
|
17
|
-
instanceId: input.instance.instanceId,
|
|
18
|
-
challenge: input.challenge,
|
|
19
|
-
challengeId: input.challengeId || "",
|
|
20
|
-
mfid: input.mfid,
|
|
21
|
-
resourceId: input.resourceId,
|
|
22
|
-
signedAt,
|
|
23
|
-
});
|
|
24
|
-
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
|
|
25
|
-
return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
|
|
26
|
-
}
|
package/src/auth/session.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { AuthInstance } from "./keys.ts";
|
|
2
|
-
import { signInstanceChallenge } from "./proof.ts";
|
|
3
|
-
import type { CloudSessionCredential, SessionClient } from "../remote/session.ts";
|
|
4
|
-
export type { CloudSessionCredential } from "../remote/session.ts";
|
|
5
|
-
|
|
6
|
-
export async function createSession(input: {
|
|
7
|
-
instance: Pick<AuthInstance, "instanceId" | "signingPrivateKey">;
|
|
8
|
-
mfid: string;
|
|
9
|
-
resourceId: string;
|
|
10
|
-
}, client: SessionClient): Promise<CloudSessionCredential> {
|
|
11
|
-
const { instance, mfid, resourceId } = input;
|
|
12
|
-
const identity = { mfid, resourceId, instanceId: instance.instanceId };
|
|
13
|
-
const challenge = await client.createChallenge(identity);
|
|
14
|
-
const proof = await signInstanceChallenge({ instance, mfid, resourceId, challengeId: challenge.challengeId, challenge: challenge.challenge });
|
|
15
|
-
return client.createSession({ ...identity, challengeId: challenge.challengeId, proof });
|
|
16
|
-
}
|
package/src/auth/store.ts
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import type { StorageAdapter } from "../bucket/store.ts";
|
|
2
|
-
import { ClientError } from "../errors.ts";
|
|
3
|
-
import { createInstanceKey, type AuthInstance } from "./keys.ts";
|
|
4
|
-
import { isPublicP256EcJwk, isValidInstanceId } from "./identifiers.ts";
|
|
5
|
-
|
|
6
|
-
type StoredInstance = AuthInstance & { updatedAt: string };
|
|
7
|
-
|
|
8
|
-
export function authRecordKeys(appId: string) {
|
|
9
|
-
const prefix = `instance:${encodeURIComponent(appId)}:`;
|
|
10
|
-
const segment = encodeURIComponent;
|
|
11
|
-
return {
|
|
12
|
-
prefix,
|
|
13
|
-
active: `${prefix}active-instance:current`,
|
|
14
|
-
keyPrefix: `${prefix}instance-key:`,
|
|
15
|
-
key: (id: string) => `${prefix}instance-key:${segment(id)}`,
|
|
16
|
-
pending: (resource: string, id: string) => `${prefix}pending-auth:${segment(resource)}:${segment(id)}`,
|
|
17
|
-
callback: (id: string) => `${prefix}callback-pointer:${segment(id)}`,
|
|
18
|
-
context: (resource: string, id: string) => `${prefix}context:${segment(resource)}:${segment(id)}`,
|
|
19
|
-
session: (resource: string, id: string) => `${prefix}session:${segment(resource)}:${segment(id)}`,
|
|
20
|
-
endpoints: (bucket: string) => `meta:${bucket}:endpoints`,
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export function createInstanceKeyStore(storage: StorageAdapter, appId: string) {
|
|
25
|
-
const keys = authRecordKeys(appId);
|
|
26
|
-
async function read(id: string): Promise<StoredInstance | null> {
|
|
27
|
-
const value = await storage.get<StoredInstance>(keys.key(id));
|
|
28
|
-
if (!value) return null;
|
|
29
|
-
if (value.v !== 1 || value.instanceId !== id || !isValidInstanceId(id)
|
|
30
|
-
|| !isPublicP256EcJwk(value.signingPublicJwk) || !isPublicP256EcJwk(value.wrappingPublicJwk)
|
|
31
|
-
|| !(value.signingPrivateKey instanceof CryptoKey) || !(value.wrappingPrivateKey instanceof CryptoKey)) {
|
|
32
|
-
throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is invalid");
|
|
33
|
-
}
|
|
34
|
-
return value;
|
|
35
|
-
}
|
|
36
|
-
async function active(): Promise<StoredInstance | null> {
|
|
37
|
-
let pointer = await storage.get<{ v: number; instanceId: string }>(keys.active);
|
|
38
|
-
if (pointer === null) {
|
|
39
|
-
if (!(await storage.keys(keys.keyPrefix)).length) return null;
|
|
40
|
-
pointer = await storage.get<{ v: number; instanceId: string }>(keys.active);
|
|
41
|
-
if (pointer === null) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key has no active pointer");
|
|
42
|
-
}
|
|
43
|
-
if (pointer.v !== 1 || !isValidInstanceId(pointer.instanceId)) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance pointer is invalid");
|
|
44
|
-
const value = await read(pointer.instanceId);
|
|
45
|
-
if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is missing");
|
|
46
|
-
return value;
|
|
47
|
-
}
|
|
48
|
-
async function insert(instance: AuthInstance): Promise<boolean> {
|
|
49
|
-
if (await storage.get(keys.active) !== null) return false;
|
|
50
|
-
const now = new Date().toISOString();
|
|
51
|
-
const entries = [{ key: keys.key(instance.instanceId), value: { ...instance, updatedAt: now } },
|
|
52
|
-
{ key: keys.active, value: { v: 1, instanceId: instance.instanceId, updatedAt: now } }];
|
|
53
|
-
if (storage.insertIfEmpty) return storage.insertIfEmpty(keys.keyPrefix, entries);
|
|
54
|
-
if ((await storage.keys(keys.keyPrefix)).length) return false;
|
|
55
|
-
const written: string[] = [];
|
|
56
|
-
try {
|
|
57
|
-
for (const entry of entries) { await storage.set(entry.key, entry.value); written.push(entry.key); }
|
|
58
|
-
} catch (error) { for (const key of written) await storage.remove(key); throw error; }
|
|
59
|
-
return true;
|
|
60
|
-
}
|
|
61
|
-
let ensuring: Promise<StoredInstance> | undefined;
|
|
62
|
-
async function save(instance: AuthInstance) {
|
|
63
|
-
if (!await insert(instance)) throw new ClientError("KEY_EXISTS", "An instance key already exists for this appId");
|
|
64
|
-
}
|
|
65
|
-
async function create(beforeWrite: () => void = () => {}) {
|
|
66
|
-
const instance = await createInstanceKey();
|
|
67
|
-
beforeWrite();
|
|
68
|
-
await save(instance);
|
|
69
|
-
return instance;
|
|
70
|
-
}
|
|
71
|
-
return {
|
|
72
|
-
keys, read, active,
|
|
73
|
-
import: save, create,
|
|
74
|
-
async remove() {
|
|
75
|
-
if (storage.removePrefix) return storage.removePrefix(keys.prefix);
|
|
76
|
-
for (const key of await storage.keys(keys.prefix)) await storage.remove(key);
|
|
77
|
-
},
|
|
78
|
-
ensure(): Promise<StoredInstance> {
|
|
79
|
-
return ensuring ??= (async () => {
|
|
80
|
-
const saved = await active();
|
|
81
|
-
if (saved) return saved;
|
|
82
|
-
try { await create(); }
|
|
83
|
-
catch (error) { if (!(error instanceof ClientError) || error.code !== "KEY_EXISTS") throw error; }
|
|
84
|
-
const value = await active();
|
|
85
|
-
if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key was not saved");
|
|
86
|
-
return value;
|
|
87
|
-
})().finally(() => { ensuring = undefined; });
|
|
88
|
-
},
|
|
89
|
-
};
|
|
90
|
-
}
|
package/src/auth/types.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import type { BucketKeyGrantEnvelope, BucketKeys } from "../bucket/keys.ts";
|
|
2
|
-
|
|
3
|
-
export type AuthCapability = "read" | "write";
|
|
4
|
-
|
|
5
|
-
export type InstanceAuthContext = {
|
|
6
|
-
v: 1;
|
|
7
|
-
mfid: string;
|
|
8
|
-
resourceId: string;
|
|
9
|
-
remoteResourceId?: string;
|
|
10
|
-
resourceApiUrl?: string;
|
|
11
|
-
instanceId: string;
|
|
12
|
-
requestId: string;
|
|
13
|
-
authorizedAt: string;
|
|
14
|
-
bucketAccessGrant?: BucketAccessGrant;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
export type BucketAccess = {
|
|
18
|
-
mfid: string;
|
|
19
|
-
instanceId: string;
|
|
20
|
-
bucketId: string;
|
|
21
|
-
resourceId: string;
|
|
22
|
-
resourceApiUrl?: string;
|
|
23
|
-
capabilities: AuthCapability[];
|
|
24
|
-
grantRecordId: string;
|
|
25
|
-
keys: BucketKeys;
|
|
26
|
-
};
|
|
27
|
-
|
|
28
|
-
export type AuthCallbackResult = {
|
|
29
|
-
requestId: string;
|
|
30
|
-
state: string;
|
|
31
|
-
result: "approved" | "denied" | "error";
|
|
32
|
-
resourceId?: string;
|
|
33
|
-
error?: string;
|
|
34
|
-
errorDescription?: string;
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
export type BucketAccessGrant = {
|
|
38
|
-
v: 1;
|
|
39
|
-
grantRecordId: string;
|
|
40
|
-
mfid: string;
|
|
41
|
-
resourceId: string;
|
|
42
|
-
instanceId: string;
|
|
43
|
-
issuedAt: string;
|
|
44
|
-
keyId: string;
|
|
45
|
-
capabilities: AuthCapability[];
|
|
46
|
-
envelope: BucketKeyGrantEnvelope;
|
|
47
|
-
};
|