@octap/browser-sdk 0.0.0-stage → 0.1.1

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/dist/client.js ADDED
@@ -0,0 +1,110 @@
1
+ export class OctaBrowserClient {
2
+ apiBaseUrl;
3
+ defaultOrganizationId;
4
+ getAuthToken;
5
+ constructor(options) {
6
+ this.apiBaseUrl = options.apiBaseUrl.replace(/\/+$/, '');
7
+ this.defaultOrganizationId = options.organizationId;
8
+ this.getAuthToken = options.getAuthToken;
9
+ }
10
+ async request(path, method = 'GET', body, orgId) {
11
+ const url = `${this.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
12
+ const headers = {
13
+ accept: 'application/json',
14
+ };
15
+ if (body !== undefined) {
16
+ headers['content-type'] = 'application/json';
17
+ }
18
+ const organizationId = orgId ?? this.defaultOrganizationId;
19
+ if (organizationId) {
20
+ headers['x-organization-id'] = organizationId;
21
+ }
22
+ if (this.getAuthToken) {
23
+ const token = await this.getAuthToken();
24
+ if (token) {
25
+ headers['authorization'] = `Bearer ${token}`;
26
+ }
27
+ }
28
+ const response = await fetch(url, {
29
+ method,
30
+ headers,
31
+ body: body !== undefined ? JSON.stringify(body) : undefined,
32
+ });
33
+ if (!response.ok) {
34
+ let errorBody = null;
35
+ try {
36
+ errorBody = await response.json();
37
+ }
38
+ catch {
39
+ errorBody = await response.text();
40
+ }
41
+ throw new Error(typeof errorBody === 'object' && errorBody !== null && 'message' in errorBody
42
+ ? String(errorBody.message)
43
+ : `Octa Browser SDK request failed: ${response.status} ${response.statusText}`);
44
+ }
45
+ return response.json();
46
+ }
47
+ /**
48
+ * Get credit balance for a member.
49
+ */
50
+ async getBalance(memberId) {
51
+ return this.request(`/v1/credits/members/${memberId}/balance`, 'GET');
52
+ }
53
+ /**
54
+ * List loyalty transactions for a member.
55
+ */
56
+ async listTransactions(memberId, limit = 50) {
57
+ return this.request(`/v1/credits/members/${memberId}/transactions?limit=${limit}`, 'GET');
58
+ }
59
+ /**
60
+ * List active vouchers in the organization.
61
+ */
62
+ async listVouchers(organizationId) {
63
+ return this.request('/v1/rewards/vouchers', 'GET', undefined, organizationId);
64
+ }
65
+ /**
66
+ * Get details of a specific voucher.
67
+ */
68
+ async getVoucher(voucherId) {
69
+ return this.request(`/v1/rewards/vouchers/${voucherId}`, 'GET');
70
+ }
71
+ /**
72
+ * Claim a voucher using loyalty points.
73
+ */
74
+ async claimVoucher(voucherId, organizationEndUserId, idempotencyKey, organizationId) {
75
+ return this.request(`/v1/rewards/vouchers/${voucherId}/claim`, 'POST', {
76
+ organizationEndUserId,
77
+ idempotencyKey: idempotencyKey ?? `claim-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
78
+ }, organizationId);
79
+ }
80
+ /**
81
+ * List all vouchers claimed/owned by a member.
82
+ */
83
+ async listMemberVouchers(memberId) {
84
+ return this.request(`/v1/rewards/members/${memberId}/vouchers`, 'GET');
85
+ }
86
+ /**
87
+ * Resolves a Google id_token (obtained from the host app's own Google Sign-In; this SDK does
88
+ * not render a sign-in button) to a zkLogin Sui address and a global end-user identity.
89
+ */
90
+ async loginWithGoogle(idToken) {
91
+ return this.request('/v1/identity/google-login', 'POST', { idToken });
92
+ }
93
+ /**
94
+ * Enrolls an already-logged-in end user into one organization's loyalty program.
95
+ */
96
+ async enroll(endUserId, organizationId, externalMemberId) {
97
+ const orgId = organizationId ?? this.defaultOrganizationId;
98
+ if (!orgId) {
99
+ throw new Error('organizationId is required (pass it or set BrowserClientOptions.organizationId)');
100
+ }
101
+ return this.request(`/v1/identity/organizations/${orgId}/enroll`, 'POST', {
102
+ endUserId,
103
+ externalMemberId,
104
+ });
105
+ }
106
+ }
107
+ export function createBrowserClient(options) {
108
+ return new OctaBrowserClient(options);
109
+ }
110
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAiBA,MAAM,OAAO,iB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ptions {
2
+ signal?: AbortSignal;
3
+ timeoutMs?: number;
4
+ }
5
+ export declare const normalizeBaseUrl: (baseUrl: string) => string;
6
+ /** The public Core routes a customer's device may call. It holds no credential of any kind. */
7
+ export declare class CoreApi {
8
+ private readonly fetchFn;
9
+ private readonly defaultTimeoutMs;
10
+ private readonly baseUrl;
11
+ constructor(baseUrl: string, fetchFn: typeof fetch, defaultTimeoutMs: number);
12
+ post<T>(path: string, payload: unknown, options?: RequestOptions): Promise<T>;
13
+ }
@@ -0,0 +1,64 @@
1
+ import { OctapAuthError } from './errors.js';
2
+ export const normalizeBaseUrl = (baseUrl) => baseUrl.replace(/\/+$/, '');
3
+ /** Reads a body once, whatever its type: an error page must not surface as a `TypeError`. */
4
+ async function readBody(response) {
5
+ const text = await response.text();
6
+ try {
7
+ return JSON.parse(text);
8
+ }
9
+ catch {
10
+ return text;
11
+ }
12
+ }
13
+ function errorMessage(response, body) {
14
+ if (typeof body === 'object' && body !== null && 'message' in body) {
15
+ return String(body.message);
16
+ }
17
+ return `OctaP request failed: ${response.status} ${response.statusText}`.trim();
18
+ }
19
+ /** The public Core routes a customer's device may call. It holds no credential of any kind. */
20
+ export class CoreApi {
21
+ fetchFn;
22
+ defaultTimeoutMs;
23
+ baseUrl;
24
+ constructor(baseUrl, fetchFn, defaultTimeoutMs) {
25
+ this.fetchFn = fetchFn;
26
+ this.defaultTimeoutMs = defaultTimeoutMs;
27
+ this.baseUrl = normalizeBaseUrl(baseUrl);
28
+ }
29
+ async post(path, payload, options = {}) {
30
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? this.defaultTimeoutMs);
31
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
32
+ let response;
33
+ let body;
34
+ try {
35
+ response = await this.fetchFn(`${this.baseUrl}${path}`, {
36
+ method: 'POST',
37
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
38
+ body: JSON.stringify(payload),
39
+ signal,
40
+ });
41
+ body = await readBody(response);
42
+ }
43
+ catch (err) {
44
+ if (options.signal?.aborted) {
45
+ throw new OctapAuthError('aborted', 'The request was aborted.');
46
+ }
47
+ if (timeout.aborted) {
48
+ throw new OctapAuthError('timeout', 'The request timed out.');
49
+ }
50
+ throw new OctapAuthError('network-error', `Could not reach OctaP: ${err?.message ?? String(err)}`);
51
+ }
52
+ if (!response.ok) {
53
+ throw new OctapAuthError('api-error', errorMessage(response, body), { status: response.status, body });
54
+ }
55
+ if (typeof body !== 'object' || body === null) {
56
+ throw new OctapAuthError('invalid-response', 'OctaP returned a response this SDK cannot read.', {
57
+ status: response.status,
58
+ body,
59
+ });
60
+ }
61
+ return body;
62
+ }
63
+ }
64
+ //# sourceMappingURL=core-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-api.js","sourceRoot":"","sources":["../src/core-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAO7C,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAAe,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAEjF,6FAA6F;AAC7F,KAAK,UAAU,QAAQ,CAAC,QAAkB;IACxC,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACnC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,YAAY,CAAC,QAAkB,EAAE,IAAa;IACrD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,SAAS,IAAI,IAAI,EAAE,CAAC;QACnE,OAAO,MAAM,CAAE,IAA6B,CAAC,OAAO,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,yBAAyB,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CA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O,EAAE,CAAC;gBACpB,MAAM,IAAI,cAAc,CAAC,SAAS,EAAE,wBAAwB,CAAC,CAAC;YAChE,CAAC;YACD,MAAM,IAAI,cAAc,CAAC,eAAe,EAAE,0BAA2B,GAAa,EAAE,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAChH,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,cAAc,CAAC,WAAW,EAAE,YAAY,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACzG,CAAC;QACD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAC9C,MAAM,IAAI,cAAc,CAAC,kBAAkB,EAAE,iDAAiD,EAAE;gBAC9F,MAAM,EAAE,QAAQ,CAAC,MAAM;gBACvB,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QACD,OAAO,IAAS,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,32 @@
1
+ export type OctapAuthErrorCode =
2
+ /** The customer closed Google's sign-in window. */
3
+ 'sign-in-canceled'
4
+ /** Google's token was not issued for this sign-in attempt. */
5
+ | 'nonce-mismatch'
6
+ /** Google's sign-in script could not load, or the SDK ran outside a browser. */
7
+ | 'provider-unavailable'
8
+ /** No customer is signed in. */
9
+ | 'not-signed-in'
10
+ /** The signing session passed its `maxEpoch`, so the customer must sign in again. */
11
+ | 'session-expired'
12
+ /** Google's id_token expired. The signing session may still work, but the backend will refuse the token. */
13
+ | 'token-expired'
14
+ /** The transaction is for a different address than the signed-in customer's. */
15
+ | 'wrong-account'
16
+ /** The claim has nothing to sign, such as a free reward that is already AVAILABLE. */
17
+ | 'invalid-claim'
18
+ /** Finalize may have reached the chain. Read the claim's state; do not sign again with a new key. */
19
+ | 'outcome-unknown'
20
+ /** The server answered with an error; see `status` and `body`. */
21
+ | 'api-error' | 'network-error' | 'timeout' | 'aborted'
22
+ /** The server answered successfully, with a body this SDK cannot use. */
23
+ | 'invalid-response';
24
+ export declare class OctapAuthError extends Error {
25
+ readonly code: OctapAuthErrorCode;
26
+ readonly status?: number;
27
+ readonly body?: unknown;
28
+ constructor(code: OctapAuthErrorCode, message: string, details?: {
29
+ status?: number;
30
+ body?: unknown;
31
+ });
32
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,13 @@
1
+ export class OctapAuthError extends Error {
2
+ code;
3
+ status;
4
+ body;
5
+ constructor(code, message, details = {}) {
6
+ super(message);
7
+ this.name = 'OctapAuthError';
8
+ this.code = code;
9
+ this.status = details.status;
10
+ this.body = details.body;
11
+ }
12
+ }
13
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AA2BA,MAAM,OAAO,cAAe,SAAQ,KAAK;IAC9B,IAAI,CAAqB;IACzB,MAAM,CAAU;IAChB,IAAI,CAAW;IAExB,YAAY,IAAwB,EAAE,OAAe,EAAE,UAA+C,EAAE;QACtG,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;CACF"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Provider sign-in: turns a click into an id_token bound to a nonce. Nothing outside this file knows
3
+ * it is Google, which keeps a later provider a change here, not in the public API.
4
+ */
5
+ export interface SignInHandlers {
6
+ onIdToken(idToken: string): void;
7
+ onCanceled(): void;
8
+ }
9
+ export interface IdTokenProvider {
10
+ render(element: HTMLElement, nonce: string, handlers: SignInHandlers): Promise<void>;
11
+ signOut(): void;
12
+ }
13
+ export declare function createGoogleProvider(clientId: string, buttonOptions?: Record<string, unknown>): IdTokenProvider;
@@ -0,0 +1,104 @@
1
+ import { OctapAuthError } from './errors.js';
2
+ const SCRIPT_URL = 'https://accounts.google.com/gsi/client';
3
+ const SCRIPT_TIMEOUT_MS = 20_000;
4
+ /** A credential can arrive just after the popup closes, so wait before calling it a cancellation. */
5
+ const CANCEL_GRACE_MS = 1_500;
6
+ const CANCEL_POLL_MS = 250;
7
+ const CANCEL_WATCH_LIMIT_MS = 5 * 60_000;
8
+ let loading;
9
+ function loadGoogleIdentity() {
10
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
11
+ return Promise.reject(new OctapAuthError('provider-unavailable', 'Google sign-in needs a browser.'));
12
+ }
13
+ const loaded = window.google?.accounts?.id;
14
+ if (loaded)
15
+ return Promise.resolve(loaded);
16
+ if (loading)
17
+ return loading;
18
+ loading = new Promise((resolve, reject) => {
19
+ const script = document.createElement('script');
20
+ script.src = SCRIPT_URL;
21
+ script.async = true;
22
+ const fail = () => {
23
+ window.clearTimeout(timer);
24
+ script.remove();
25
+ loading = undefined;
26
+ reject(new OctapAuthError('provider-unavailable', 'Google sign-in could not load.'));
27
+ };
28
+ const timer = window.setTimeout(fail, SCRIPT_TIMEOUT_MS);
29
+ script.onerror = fail;
30
+ script.onload = () => {
31
+ const google = window.google?.accounts?.id;
32
+ if (!google) {
33
+ fail();
34
+ return;
35
+ }
36
+ window.clearTimeout(timer);
37
+ resolve(google);
38
+ };
39
+ document.head.appendChild(script);
40
+ });
41
+ return loading;
42
+ }
43
+ export function createGoogleProvider(clientId, buttonOptions = {}) {
44
+ let google;
45
+ let stopWatching;
46
+ return {
47
+ async render(element, nonce, handlers) {
48
+ google = await loadGoogleIdentity();
49
+ google.initialize({
50
+ client_id: clientId,
51
+ auto_select: false,
52
+ nonce,
53
+ callback: ({ credential }) => {
54
+ stopWatching?.();
55
+ handlers.onIdToken(credential);
56
+ },
57
+ });
58
+ google.renderButton(element, {
59
+ theme: 'outline',
60
+ size: 'large',
61
+ ...buttonOptions,
62
+ click_listener: () => {
63
+ stopWatching?.();
64
+ stopWatching = watchForCancel(handlers.onCanceled);
65
+ },
66
+ });
67
+ },
68
+ signOut() {
69
+ stopWatching?.();
70
+ google?.disableAutoSelect();
71
+ },
72
+ };
73
+ }
74
+ /**
75
+ * Google's button reports no cancellation. Its popup takes focus from this document and gives it back
76
+ * when it closes, so focus returning with no credential after a short wait means it was closed. This
77
+ * polls because Google's button is a cross-origin iframe, which makes `blur` and `focus` events on the
78
+ * window fire unreliably. A customer who clicks back while the popup is open also looks like this,
79
+ * and a credential arriving afterwards still completes the sign-in.
80
+ */
81
+ function watchForCancel(onCanceled) {
82
+ const startedAt = Date.now();
83
+ let popupSeen = false;
84
+ let focusedSince;
85
+ const timer = window.setInterval(() => {
86
+ if (Date.now() - startedAt >= CANCEL_WATCH_LIMIT_MS) {
87
+ stop();
88
+ }
89
+ else if (!document.hasFocus()) {
90
+ popupSeen = true;
91
+ focusedSince = undefined;
92
+ }
93
+ else if (popupSeen) {
94
+ focusedSince ??= Date.now();
95
+ if (Date.now() - focusedSince >= CANCEL_GRACE_MS) {
96
+ stop();
97
+ onCanceled();
98
+ }
99
+ }
100
+ }, CANCEL_POLL_MS);
101
+ const stop = () => window.clearInterval(timer);
102
+ return stop;
103
+ }
104
+ //# sourceMappingURL=google-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"google-provider.js","sourceRoot":"","sources":["../src/google-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA6B7C,MAAM,UAAU,GAAG,wCAAwC,CAAC;AAC5D,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,qGAAqG;AACrG,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,qBAAqB,GAAG,CAAC,GAAG,MAAM,CAAC;AAEzC,IAAI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,YAAgC,CAAC;IACrC,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE;QACpC,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,IAAI,qBAAqB,EAAE,CAAC;YACpD,IAAI,EAAE,CAAC;QACT,CAAC;aAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC;YAChC,SAAS,GAAG,IAAI,CAAC;YACjB,YAAY,GAAG,SAAS,CAAC;QAC3B,CAAC;aAAM,IAAI,SAAS,EAAE,CAAC;YACrB,YAAY,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC;YAC5B,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,IAAI,eAAe,EAAE,CAAC;gBACjD,IAAI,EAAE,CAAC;gBACP,UAAU,EAAE,CAAC;YACf,CAAC;QACH,CAAC;IACH,CAAC,EAAE,cAAc,CAAC,CAAC;IACnB,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { OctapAuth, createOctapAuth, type AuthStateListener, type FinalizedClaim, type FinalizedVoucherUse, type OctapAuthOptions, type RenderOptions, type SignableClaim, type SignableVoucherUse, } from './auth.js';
2
+ export type { RequestOptions } from './core-api.js';
3
+ export { OctapAuthError, type OctapAuthErrorCode } from './errors.js';
4
+ export type { OctapUser, Persistence } from './session-store.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { OctapAuth, createOctapAuth, } from './auth.js';
2
+ export { OctapAuthError } from './errors.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,eAAe,GAQhB,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { type SignerState } from './zklogin-signer.js';
2
+ export interface OctapUser {
3
+ endUserId: string;
4
+ /** The customer's `organizationEndUserId` in this organization. */
5
+ memberId: string;
6
+ suiAddress: string;
7
+ }
8
+ export interface StoredSession {
9
+ user: OctapUser;
10
+ idToken: string;
11
+ signer: SignerState;
12
+ }
13
+ export type Persistence = 'session' | 'memory';
14
+ export interface SessionStore {
15
+ load(): StoredSession | null;
16
+ save(session: StoredSession): void;
17
+ clear(): void;
18
+ }
19
+ /** A session belongs to one configuration: another API or Google client must not restore it. */
20
+ export interface SessionScope {
21
+ apiBaseUrl: string;
22
+ googleClientId: string;
23
+ organizationId: string;
24
+ }
25
+ export declare function createSessionStore(persistence: Persistence, scope: SessionScope): SessionStore;
@@ -0,0 +1,79 @@
1
+ import { isZkProof } from './zklogin-signer.js';
2
+ function memoryStore() {
3
+ let held = null;
4
+ return {
5
+ load: () => held,
6
+ save: (session) => {
7
+ held = session;
8
+ },
9
+ clear: () => {
10
+ held = null;
11
+ },
12
+ };
13
+ }
14
+ function isStoredSession(value) {
15
+ const session = value;
16
+ return (typeof session?.user?.endUserId === 'string' &&
17
+ typeof session.user.memberId === 'string' &&
18
+ typeof session.user.suiAddress === 'string' &&
19
+ typeof session.idToken === 'string' &&
20
+ typeof session.signer?.secretKey === 'string' &&
21
+ typeof session.signer.maxEpoch === 'number' &&
22
+ typeof session.signer.expiresAt === 'number' &&
23
+ isZkProof(session.signer.proof));
24
+ }
25
+ /**
26
+ * Browser storage can be missing or throw (private windows, blocked site data). Losing it must only
27
+ * cost a sign-in after reload, so every access falls back to the copy held in memory.
28
+ */
29
+ function browserStore(storage, key) {
30
+ const memory = memoryStore();
31
+ return {
32
+ load() {
33
+ try {
34
+ const raw = storage.getItem(key);
35
+ const parsed = raw ? JSON.parse(raw) : null;
36
+ if (isStoredSession(parsed))
37
+ return parsed;
38
+ if (raw)
39
+ storage.removeItem(key);
40
+ }
41
+ catch {
42
+ // Unreadable storage is the same as no stored session.
43
+ }
44
+ return memory.load();
45
+ },
46
+ save(session) {
47
+ memory.save(session);
48
+ try {
49
+ storage.setItem(key, JSON.stringify(session));
50
+ }
51
+ catch {
52
+ // Kept in memory only: the session lasts until reload.
53
+ }
54
+ },
55
+ clear() {
56
+ memory.clear();
57
+ try {
58
+ storage.removeItem(key);
59
+ }
60
+ catch {
61
+ // Nothing could have been written either.
62
+ }
63
+ },
64
+ };
65
+ }
66
+ export function createSessionStore(persistence, scope) {
67
+ if (persistence === 'memory')
68
+ return memoryStore();
69
+ let storage;
70
+ try {
71
+ storage = globalThis.sessionStorage;
72
+ }
73
+ catch {
74
+ storage = undefined;
75
+ }
76
+ const key = `octap.auth.${JSON.stringify([scope.apiBaseUrl, scope.googleClientId, scope.organizationId])}`;
77
+ return storage ? browserStore(storage, key) : memoryStore();
78
+ }
79
+ //# sourceMappingURL=session-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-store.js","sourceRoot":"","sources":["../src/session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,qBAAqB,CAAC;AAuBlE,SAAS,WAAW;IAClB,IAAI,IAAI,GAAyB,IAAI,CAAC;IACtC,OAAO;QACL,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI;QAChB,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE;YAChB,IAAI,GAAG,OAAO,CAAC;QACjB,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,IAAI,GAAG,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACrC,MAAM,OAAO,GAAG,KAAsC,CAAC;IACvD,OAAO,CACL,OAAO,OAAO,EAAE,IAAI,EAAE,SAAS,KAAK,QAAQ;QAC5C,OAAO,OAAO,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ;QACzC,OAAO,OAAO,CAAC,IAAI,CAAC,UAAU,KAAK,Q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AAC,MAAM,CAAC;gBACP,0CAA0C;YAC5C,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AASD,MAAM,UAAU,kBAAkB,CAAC,WAAwB,EAAE,KAAmB;IAC9E,IAAI,WAAW,KAAK,QAAQ;QAAE,OAAO,WAAW,EAAE,CAAC;IACnD,IAAI,OAA4B,CAAC;IACjC,IAAI,CAAC;QACH,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC;IACtC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,SAAS,CAAC;IACtB,CAAC;IACD,MAAM,GAAG,GAAG,cAAc,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC;IAC3G,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { type ZkLoginSignatureInputs } from '@mysten/sui/zklogin';
2
+ import type { CoreApi } from './core-api.js';
3
+ export interface SignerState {
4
+ secretKey: string;
5
+ maxEpoch: number;
6
+ /** Core's estimate of when `maxEpoch` ends, in milliseconds since the epoch. */
7
+ expiresAt: number;
8
+ proof: ZkLoginSignatureInputs;
9
+ }
10
+ export declare function isZkProof(value: unknown): value is ZkLoginSignatureInputs;
11
+ /** A key and nonce waiting for the customer to sign in. */
12
+ export declare class PendingSignIn {
13
+ private readonly keypair;
14
+ private readonly params;
15
+ private constructor();
16
+ static start(api: CoreApi): Promise<PendingSignIn>;
17
+ get nonce(): string;
18
+ /** A flow check, not token validation: Enoki validates the token's signature. */
19
+ assertIssuedForThisAttempt(idToken: string): void;
20
+ prove(api: CoreApi, idToken: string): Promise<SignerState>;
21
+ }
22
+ /** Seconds since the epoch at which an id_token stops being valid, or undefined if unreadable. */
23
+ export declare function idTokenExpiry(idToken: string): number | undefined;
24
+ /** Signs for the signed-in customer, refusing bytes that name a different sender. */
25
+ export declare function signWithZkLogin(state: SignerState, suiAddress: string, transactionBytes: string): Promise<string>;
@@ -0,0 +1,111 @@
1
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
2
+ import { Transaction } from '@mysten/sui/transactions';
3
+ import { fromBase64 } from '@mysten/sui/utils';
4
+ import { getZkLoginSignature } from '@mysten/sui/zklogin';
5
+ import { OctapAuthError } from './errors.js';
6
+ export function isZkProof(value) {
7
+ const proof = value;
8
+ return (typeof proof?.addressSeed === 'string' &&
9
+ typeof proof.headerBase64 === 'string' &&
10
+ typeof proof.issBase64Details?.value === 'string' &&
11
+ Array.isArray(proof.proofPoints?.a) &&
12
+ Array.isArray(proof.proofPoints.b) &&
13
+ Array.isArray(proof.proofPoints.c));
14
+ }
15
+ /** A key and nonce waiting for the customer to sign in. */
16
+ export class PendingSignIn {
17
+ keypair;
18
+ params;
19
+ constructor(keypair, params) {
20
+ this.keypair = keypair;
21
+ this.params = params;
22
+ }
23
+ static async start(api) {
24
+ const keypair = new Ed25519Keypair();
25
+ const params = await api.post('/v1/identity/zklogin/nonce', {
26
+ ephemeralPublicKey: keypair.getPublicKey().toSuiPublicKey(),
27
+ });
28
+ if (typeof params.nonce !== 'string' ||
29
+ !params.nonce ||
30
+ typeof params.randomness !== 'string' ||
31
+ !Number.isFinite(params.maxEpoch) ||
32
+ !Number.isFinite(params.estimatedExpiration)) {
33
+ throw new OctapAuthError('invalid-response', 'OctaP returned an invalid sign-in nonce.', { body: params });
34
+ }
35
+ return new PendingSignIn(keypair, params);
36
+ }
37
+ get nonce() {
38
+ return this.params.nonce;
39
+ }
40
+ /** A flow check, not token validation: Enoki validates the token's signature. */
41
+ assertIssuedForThisAttempt(idToken) {
42
+ if (Date.now() >= this.params.estimatedExpiration) {
43
+ throw new OctapAuthError('session-expired', 'This sign-in attempt expired. Sign in again.');
44
+ }
45
+ let nonce;
46
+ try {
47
+ nonce = decodePayload(idToken).nonce;
48
+ }
49
+ catch {
50
+ throw new OctapAuthError('nonce-mismatch', 'Google returned an unreadable token. Sign in again.');
51
+ }
52
+ if (nonce !== this.params.nonce) {
53
+ throw new OctapAuthError('nonce-mismatch', 'Google sign-in did not match this attempt. Sign in again.');
54
+ }
55
+ }
56
+ async prove(api, idToken) {
57
+ const proof = await api.post('/v1/identity/zklogin/proof', {
58
+ idToken,
59
+ ephemeralPublicKey: this.keypair.getPublicKey().toSuiPublicKey(),
60
+ randomness: this.params.randomness,
61
+ maxEpoch: this.params.maxEpoch,
62
+ });
63
+ if (!isZkProof(proof)) {
64
+ throw new OctapAuthError('invalid-response', 'OctaP returned an invalid signing proof.', { body: proof });
65
+ }
66
+ return {
67
+ secretKey: this.keypair.getSecretKey(),
68
+ maxEpoch: this.params.maxEpoch,
69
+ expiresAt: this.params.estimatedExpiration,
70
+ proof,
71
+ };
72
+ }
73
+ }
74
+ function decodePayload(idToken) {
75
+ const payload = idToken.split('.')[1];
76
+ const bytes = Uint8Array.from(atob(payload.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
77
+ return JSON.parse(new TextDecoder().decode(bytes));
78
+ }
79
+ /** Seconds since the epoch at which an id_token stops being valid, or undefined if unreadable. */
80
+ export function idTokenExpiry(idToken) {
81
+ try {
82
+ const { exp } = decodePayload(idToken);
83
+ return typeof exp === 'number' ? exp : undefined;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /** Signs for the signed-in customer, refusing bytes that name a different sender. */
90
+ export async function signWithZkLogin(state, suiAddress, transactionBytes) {
91
+ let bytes;
92
+ let sender;
93
+ try {
94
+ bytes = fromBase64(transactionBytes);
95
+ sender = Transaction.from(bytes).getData().sender;
96
+ }
97
+ catch {
98
+ throw new OctapAuthError('invalid-claim', 'These transaction bytes cannot be read.');
99
+ }
100
+ if (sender !== suiAddress) {
101
+ throw new OctapAuthError('wrong-account', 'This transaction belongs to a different account than the one signed in. Sign in with that account.');
102
+ }
103
+ try {
104
+ const { signature: userSignature } = await Ed25519Keypair.fromSecretKey(state.secretKey).signTransaction(bytes);
105
+ return getZkLoginSignature({ inputs: state.proof, maxEpoch: state.maxEpoch, userSignature });
106
+ }
107
+ catch {
108
+ throw new OctapAuthError('session-expired', 'The signing session cannot be used. Sign in again.');
109
+ }
110
+ }
111
+ //# sourceMappingURL=zklogin-signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zklogin-signer.js","sourceRoot":"","sources":["../src/zklogin-signer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,mBAAmB,EAA+B,MAAM,qBAAqB,CAAC;AAEvF,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAsB7C,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,MAAM,KAAK,GAAG,KAA+C,CAAC;IAC9D,OAAO,CACL,OAAO,KAAK,EAAE,WAAW,KAAK,QAAQ;QACtC,OAAO,KAAK,CAAC,YAAY,KAAK,QAAQ;QACtC,OAAO,KAAK,CAAC,gBAAgB,EAAE,KAAK,KAAK,QAAQ;QACjD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC;QACnC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;QAClC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CACnC,CAAC;AACJ,CAAC;AAED,2DAA2D;AAC3D,MAAM,OAAO,aAAa;IAEL;IACA;IAFnB,YACmB,OAAuB,EACvB,MAAqB;QADrB,YAAO,GAAP,OAAO,CAAgB;QACvB,WAAM,GAAN,MAAM,CAAe;IACrC,CAAC;IAEJ,MAAM,CAAC,KAAK,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